java 在所有 SpringBeans 和 ApplicationContext 初始化后调用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3409605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling A Method After all SpringBeans and ApplicationContext have been initialized
提问by Kelly
I have a method in a complex java program that needs to be called immediately after the web ApplicationContext and SpringBeans have been initialized.
我在一个复杂的 java 程序中有一个方法,需要在 web ApplicationContext 和 SpringBeans 初始化后立即调用。
I've tried toying around with
<bean id="..." class="..." init-method="initialize">but this method will call a applicationContext.get().getBean(beanId);method.
我试过玩弄,
<bean id="..." class="..." init-method="initialize">但这个方法会调用一个applicationContext.get().getBean(beanId);方法。
I was wondering if anyone knows how to do this.
我想知道是否有人知道如何做到这一点。
Thank you.
谢谢你。
采纳答案by axtavt
You may catch a ContextRefreshedEventwith ApplicationListener.
你可能会遇到一个ContextRefreshedEventwith ApplicationListener。
回答by Herbie Porter
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.
在 Spring 4.2 之后,您可以使用注释将事件侦听器附加到 Springs Lifecycle 事件(和您自己的事件)。简单地将@EventListener 添加到一个方法中,并将事件类型作为第一个(也是唯一的)参数包含在内,Spring 将自动检测它并将其连接起来。
https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2
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) {
...
}
}
回答by Shafin Mahmud
You can use ApplicationListener<E>for this purpose. In the generic type parameter you could use ContextRefreshedEventfor you requirement. And keep note that, in the overridden method onApplicationEventyou 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
您可以ApplicationListener<E>为此目的使用。在泛型类型参数中,您可以根据ContextRefreshedEvent需要使用。请注意,在重写的方法中,onApplicationEvent您可以执行任何操作,例如自动装配 bean 或将其用作服务或从此处调用另一个服务。并注意它与@PostConstructor
public class MyContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//do what you want
}
}
回答by earldouglas
You could add a custom BeanFactoryPostProcessorwhich has access to the bean in question.
您可以添加一个自定义BeanFactoryPostProcessor,它可以访问有问题的 bean。

