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.

- 511
- 4
- 9
- 23
3 Answers
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
}
}

- 2,753
- 2
- 19
- 23
You can use Spring's event handling. The event that you are looking for is probably ContextRefreshedEvent

- 60,071
- 24
- 172
- 190
Yes you need to add ContextLoaderListener in web.xml, only if you want to load other Spring context xml files as well while loading the app and you can specify them as
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
for more u can visit this link might helpful to you.

- 1
- 1

- 2,647
- 4
- 24
- 38