public class IOCTest_Ext {
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class);
//发布事件;
applicationContext.publishEvent(new ApplicationEvent(new String("我发布的时间")) {
});
applicationContext.close();
}
}
listen监听事件
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
//当容器中发布此事件以后,方法触发
@Override
public void onApplicationEvent(ApplicationEvent event) {
// TODO Auto-generated method stub
System.out.println("收到事件:" event);
}
}
结果
收到事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@6d86b085: startup date [Wed Apr 10 06:59:46 CST 2019]; root of context hierarchy]
收到事件:com.atguigu.test.IOCTest_Ext$1[source=我发布的时间]
收到事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@6d86b085: startup date [Wed Apr 10 06:59:46 CST 2019]; root of context hierarchy]
有三个结果:分别是容器刷新、关闭的事件,还有一个是我们自定义的。
也可以使用更方便的注解的方式,效果是一样的
@Service
public class UserService {
@EventListener(classes={ApplicationEvent.class})
public void listen(ApplicationEvent event){
System.out.println("UserService。。监听到的事件:" event);
}
}
结果
UserService。。监听到的事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@6d86b085: startup date [Wed Apr 10 07:01:54 CST 2019]; root of context hierarchy]
UserService。。监听到的事件:com.atguigu.test.IOCTest_Ext$1[source=我发布的时间]
UserService。。监听到的事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@6d86b085: startup date [Wed Apr 10 07:01:54 CST 2019]; root of context hierarchy]