In my web application, I want to create Listener which will get notified when my server get started and all bean get loaded.
In that Listener, I want to call a service method.
I used ServletContextListener
.
it has contextInitialized
method but it does not work in my case. it get involked when server get started but before spring bean creation.
so I get instance of service class as null.
Is there other way to create Listener.
I would go for registering an instance of ApplicationListener in the Spring context configuration, that listens for the ContextRefreshedEvent, which is signalled when the application context has finished initializing or being refreshed. After this moment you could call your service.
Below you will find the ApplicationListener implementation (which depends on the service) and the Spring configuration (both Java and XML)that you need to achieve this. You need to choose the configuration specific to your app:
Java-based configuration
@Configuration
public class JavaConfig {
@Bean
public ApplicationListener<ContextRefreshedEvent> contextInitFinishListener() {
return new ContextInitFinishListener(myService());
}
@Bean
public MyService myService() {
return new MyService();
}
}
XML
<bean class="com.package.ContextInitFinishListener">
<constructor-arg>
<bean class="com.package.MyService"/>
</constructor-arg>
</bean>
This is the code for the ContextInitFinishListener class:
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class ContextInitFinishListener implements ApplicationListener<ContextRefreshedEvent> {
private MyService myService;
public ContextInitFinishListener(MyService myService) {
this.myService = myService;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//call myService
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With