I have a method in a complex java program that needs to be called immediately after the web ApplicationContext and SpringBeans have been initialized.
I've tried toying around with
<bean id="..." class="..." init-method="initialize">
but this method will call a applicationContext.get().getBean(beanId);
method.
I was wondering if anyone knows how to do this.
Thank you.
Using @PostConstruct One of the ways to run your code right after a Bean has been initialized is to use @PostConstract annotation. In the below code example the class MyBean is annotated with @Component annotation. This Bean will be created at application startup time. Note the use of @PostConstruct annotation.
The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation.
Using Annotation: To provide the facility to the created bean to invoke custom init() method on the startup of a spring container and to invoke the custom destroy() method on closing the container, we need annotate init() method by @PostConstruct annotation and destroy() method by @PreDestroy annotation.
In Spring 4.2 onwards you can attach event listeners to Springs Lifecycle events (and your own) using annotations. Simple add the @EventListener to a method and include the event type as the first (and only) parameter and Spring will automatically detect it and wire it up.
https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2
@Component
public class MyListener {
@EventListener
public void handleContextRefresh(ContextRefreshedEvent event) {
...
}
}
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