Calling A Method After all SpringBeans and Applica

2020-02-13 07:22发布

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.

标签: java spring
4条回答
Rolldiameter
2楼-- · 2020-02-13 07:49

You can use ApplicationListener<E> for this purpose. In the generic type parameter you could use ContextRefreshedEvent for you requirement. And keep note that, in the overridden method onApplicationEvent you can do anything like autowire a bean or use it as a service or call another service from here. And note that how its different from @PostConstructor

public class MyContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //do what you want
    }
}
查看更多
干净又极端
3楼-- · 2020-02-13 07:58

You may catch a ContextRefreshedEvent with ApplicationListener.

查看更多
祖国的老花朵
4楼-- · 2020-02-13 07:59

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) {
        ...
    }
}
查看更多
姐就是有狂的资本
5楼-- · 2020-02-13 08:12

You could add a custom BeanFactoryPostProcessor which has access to the bean in question.

查看更多
登录 后发表回答