0

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.

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
Jaabax
  • 155
  • 2
  • 8
  • 1
    @PostConstruct on init method might help you – Jekin Kalariya Sep 02 '16 at 03:28
  • http://stackoverflow.com/questions/17557214/run-code-once-spring-app-is-succesfully-deployed – amicoderozer Sep 02 '16 at 07:50
  • @JekinKalariya but with PostConstruct I will need to tie my initializer with my beans... my initializer is something independent of any business or component in my application... I just need like a "main" method that will be execute once and will fill some variables with data (like path to the server and etc) – Jaabax Sep 02 '16 at 17:14
  • @amicoderozer thanks for the link... checking.. – Jaabax Sep 02 '16 at 17:16

1 Answers1

1

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

Duncan
  • 696
  • 1
  • 5
  • 15
  • hmm that seems a good approach because I don't want my initializer tied to any of my beans... and I do not want to create a @entity/repository/service just for this... the only thing my initializer does is to take the .class of the @Entities in the class path and store in a static variable (because later screens will be automatically generated with these .classes) – Jaabax Sep 02 '16 at 17:11
  • I'm glad it helped you. Sometimes contextRefreshedEvent called twice because bad configuration, here is the solution. http://stackoverflow.com/questions/6164573/why-is-my-spring-contextrefreshed-event-called-twice – Duncan Sep 05 '16 at 02:44
  • Just in case you need it. :) – Duncan Sep 05 '16 at 02:45