调用方法在初始化所有SpringBeans和ApplicationContext之后

Kel*_*lly 16 java spring

我在一个复杂的java程序中有一个方法,需要在初始化Web ApplicationContext和SpringBeans之后立即调用它.

我试过玩弄 <bean id="..." class="..." init-method="initialize"> 但这个方法会调用一个applicationContext.get().getBean(beanId);方法.

我想知道是否有人知道如何做到这一点.

谢谢.

Her*_*ter 18

在Spring 4.2之后,您可以使用注释将事件监听器附加到Springs Lifecycle事件(和您自己的事件).简单地将@EventListener添加到方法并将事件类型包含为第一个(也是唯一的)参数,Spring将自动检测它并将其连接起来.

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) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)


axt*_*avt 14

您可以赶上ContextRefreshedEventApplicationListener.


Sha*_*mud 5

您可以用于ApplicationListener<E>此目的。在泛型类型参数中,您可以ContextRefreshedEvent根据您的要求使用。请注意,在重写的方法中,onApplicationEvent您可以执行任何操作,例如自动装配 bean 或将其用作服务或从此处调用另一个服务。并注意它与@PostConstructor

public class MyContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //do what you want
    }
}
Run Code Online (Sandbox Code Playgroud)