Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listener for server starup and all spring bean loaded completely

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.

like image 767
Prithvipal Singh Avatar asked Feb 14 '23 05:02

Prithvipal Singh


1 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
    }
}
like image 125
Gabriel Ruiu Avatar answered Feb 17 '23 22:02

Gabriel Ruiu