Java listen ContextRefreshedEvent

I have class X in my spring application in which I want to find out if all spring beans have been initialized. For this, I'm trying to listen to ContextRefreshedEvent.

So far I have the following code, but I'm 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 right to find out if all beans were initials?
  • What else do I need to do to listen to ContextRefreshedEvent? Do I need to register class X somewhere in xml files?
+6
source share
2 answers

A ContextRefreshEvent occurs

when ApplicationContext initialized or updated.

so that you are on the right track.

What you need to do is declare a bean definition for classX .

Either using @Component or through component scan of a component in

 @Component public classX implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { //do something if all apps have initialised } } 

or with the declaration <bean>

 <bean class="some.pack.classX"></bean> 

Spring will detect that the bean is of type ApplicationListener and register it without any additional configuration.


Just FYI, Java has naming conventions for types, variables, etc. For classes, the convention is that their names begin with an uppercase alphabetic character.

+14
source

Spring> = 4.2

You can use an annotation driven event listener as shown below:

 @Component public class classX { @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { } } 

The ApplicationListener that you want to register is defined in the method signature .

+3
source

Source: https://habr.com/ru/post/959012/


All Articles