Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code once Spring app is successfully deployed

Is there a way in a Spring app to know when the initialization has finished? I have to run some code once my app is deployed and I'm searching something like ServletContextListener or Spring built-in events.

like image 651
David Moreno García Avatar asked Jul 09 '13 20:07

David Moreno García


2 Answers

Based on your response to my comment I will respond with the multiple things you can do to process an initialized Spring bean.

  1. You can utilize a BeanPostProcessor. It has two methods that are treated as callbacks, and I believe that postProcessAfterInitialization is the one that you would be interested in. The thing with BeanPostProcessor's is that they are run for each bean in the ApplicationContext, so you will want to be sure to look for only the bean(s) that you are interested in applying this processing to. To use a BeanPostProcessor, you simply define it as a part of your ApplicationContext.
  2. Implement the InitializingBean interface. It defines a single method afterPropertiesSet which is invoked by the ApplicationContext. This has an advantage over number 1, as it can be applied on a bean by bean basis (doesn't apply to all beans in ApplicationContext).
  3. Utilize the @PostContstuct annotation on a method. This annotation tells the ApplicationContext that this method should be run after the bean has been initialized. This acts similarly to number 2, in that it is performed on a bean by bean basis.

Further information on the callback lifecycle of the ApplicationContext can be read about at this location.

like image 175
nicholas.hauschild Avatar answered Sep 23 '22 08:09

nicholas.hauschild


You can use

  • @PostConstruct annotation
  • or a ApplicationListener that get triggered by the ContextStartedEvent (but take care if you have a typical web application you have two contexts and so two ContextStartedEvents.
like image 26
Ralph Avatar answered Sep 25 '22 08:09

Ralph