And*_*ich 39 java spring listener applicationcontext
我有以下ApplicationListener:
package org.mycompany.listeners;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
public class MyApplicationListener implements ApplicationListener<ContextStartedEvent> {
public MyApplicationListener() {
super();
System.out.println("Application context listener is created!");
}
/**
* {@inheritDoc}
*/
public void onApplicationEvent(final ContextStartedEvent event) {
System.out.println("Context '" + event.getApplicationContext().getDisplayName() + "' is started!");
}
}
Run Code Online (Sandbox Code Playgroud)
以下bean定义:
<bean name="myApplicationListener" class="org.mycompany.listeners.MyApplicationListener" />
Run Code Online (Sandbox Code Playgroud)
我可以看到bean是在打印构造函数的消息时创建的,但是从不收到上下文启动事件.我错过了什么?
axt*_*avt 62
ContextStartedEvent在显式调用ConfigurableApplicationContext.start()上下文时发布.如果需要在初始化上下文时发布的事件,请使用ContextRefreshedEvent.
也可以看看:
由于你没有延迟加载的bean(根据你),你很可能出于错误的原因使用事件,并且可能应该使用类似InitializingBean接口的东西:
public class MyBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
从Spring手册:
要与容器的bean生命周期管理进行交互,可以实现Spring InitializingBean和DisposableBean接口.容器为前者调用afterPropertiesSet(),为后者调用destroy()以允许bean在初始化和销毁bean时执行某些操作.您还可以实现与容器的相同集成,而无需通过使用init-method和destroy方法对象定义元数据将类耦合到Spring接口.
| 归档时间: |
|
| 查看次数: |
40521 次 |
| 最近记录: |