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.
Based on your response to my comment I will respond with the multiple things you can do to process an initialized Spring bean.
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
.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
).@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.
You can use
@PostConstruct
annotationApplicationListener
that get triggered by the ContextStartedEvent
(but take care if you have a typical web application you have two contexts and so two ContextStartedEvent
s.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With