1.定义时间监听
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
//当容器中发布此事件以后,方法触发
public void onApplicationEvent(ApplicationEvent event) {
// TODO Auto-generated method stub
System.out.println("收到事件:"+event);
}
}
2.使用注解,在指定的位置上监听
@Service
public class UserService {
@EventListener(classes={ApplicationEvent.class})
public void listen(ApplicationEvent event){
System.out.println("UserService。。监听到的事件:"+event);
}
}
3.发布事件
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class);
//发布事件;
applicationContext.publishEvent(new ApplicationEvent(new String("我发布的时间")) {
});
applicationContext.close();
console....
UserService。。监听到的事件:com.atguigu.test.hou.IOCTest_Ext$1[source=我发布的时间]
收到事件:com.atguigu.test.hou.IOCTest_Ext$1[source=我发布的时间]
UserService。。监听到的事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@3339ad8e: startup date [Tue Aug 06 18:41:16 CST 2019]; root of context hierarchy]
收到事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@3339ad8e: startup date [Tue Aug 06 18:41:16 CST 2019]; root of context hierarchy]