Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling A Method After all SpringBeans and ApplicationContext have been initialized

Tags:

java

spring

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.

like image 909
Kelly Avatar asked Aug 04 '10 20:08

Kelly


People also ask

How do you execute a method after all beans are initialized?

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.

Which method is called after Bean instantiation?

The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation.

How do you initialize a bean in spring?

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.


1 Answers

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) {
        ...
    }
}
like image 109
Herbie Porter Avatar answered Sep 23 '22 15:09

Herbie Porter