@Component
public class LeonApplicationListener implements ApplicationListener {
//接受到消息,回调该方法
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println("LeonApplicationListener 接受到了一个事件"+event);
}
}
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
//手动发布一个事件
ctx.publishEvent(new ApplicationEvent("我手动发布了一个事件") {
@Override
public Object getSource() {
return super.getSource();
}
});
//容器关闭也发布事件
ctx.close();
}
测试结果:
LeonApplicationListener 接受到了一个事件org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@37bba400 hierarchy]
LeonApplicationListener 接受到了一个事件com.Leon.testapplicationlistener.MainClass$1[source=我手动发布了一个事件]
LeonApplicationListener 接受到了一个事件org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@37bba400 hierarchy]