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

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

我尝试过使用但这个方法将调用applicationContext.get().getBean(beanId); 方法。

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

谢谢。

您可以使用ApplicationListener捕获ContextRefreshedEvent

在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) { ... } } 

您可以使用ApplicationListener来实现此目的。 在generics类型参数中,您可以根据需要使用ContextRefreshedEvent 。 请注意,在重写的方法onApplicationEvent您可以执行任何操作,例如autowire bean或将其用作服务或从此处调用其他服务。 并注意它与@PostConstructor不同之处

 public class MyContextRefreshListener implements ApplicationListener { @Override public void onApplicationEvent(ContextRefreshedEvent event) { //do what you want } } 

您可以添加一个自定义BeanFactoryPostProcessor ,它可以访问相关的bean。