Search code examples
springwebinitializationinitializer

Calling a Spring @Service on web application initialization


I have a web application that needs some static variables initialization as soon as I thrown the .war in the Tomcat webapp folder. This initialization needs to call a @Service to retrieve the initial set up.

I realized that the @Autowire injection only works when my GUI is calling the service

What is the best way to initialize my Spring web application after throwing the .war in the app container? I need this initialization to be executed once only.


Solution

  • If you need to do something after servletContext is initialized, in spring, we use ApplicationListener to do this.

    public class SpringListener implements ApplicationListener<ContextRefreshedEvent>{
    
            // this should work if other setting is right  
            @Autowired
            XXX xxx;
    
            public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent ) {
                     // do things here
            }
        }
    
    in application.xml
    <bean id="eventListenerBean" class="package.name.SpringListener " />
    

    http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#context-functionality-events

    On the otherhand, just FYI, the traditional way is to do it using ServletContextListener. http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html