I have a classX in my spring application in which I want to be able to find out if all spring beans have been initialized. To do this, I am trying to listen ContextRefreshedEvent.
So far I have the following code but I am not sure if this is enough.
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public classX implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//do something if all apps have initialised
}
}
- Is this approach correct to find out if all beans have initialsed?
- What else do I need to do to be able to listen to the ContextRefreshedEvent ? DO I need to register classX somewhere in xml files ?
A ContextRefreshEvent occurs
when an
ApplicationContextgets initialized or refreshed.
so you are on the right track.
What you need to do is declare a bean definition for classX.
Either with @Component and a component scan over the package it's in
@Component
public classX implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//do something if all apps have initialised
}
}
or with a <bean> declaration
<bean class="some.pack.classX"></bean>
Spring will detect that the bean is of type ApplicationListener and register it without any further configuration.
Just FYI, Java has naming conventions for types, variables, etc. For classes, the convention is to have their names start with an uppercase alphabetic character.
Spring >= 4.2
You can use annotation-driven event listener as below :
@Component
public class classX {
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
}
}
the ApplicationListener you want to register is defined in the signature of the method.
来源:https://stackoverflow.com/questions/20275952/java-listen-to-contextrefreshedevent