08.Spring 应用之 Event

时光总嘲笑我的痴心妄想 提交于 2020-02-12 02:06:59

代码已经上传至 https://github.com/masteryourself/study-spring.git ,分支是 master,工程是 study-spring-framework

1. Event

1.1 ApplicationListener

  • 监听容器中发布的事件,事件驱动模型开发

  • 监听 ApplicationEvent 及其子类的事件

1.2 @EventListener

  • 可以使用注解简化开发,原理是通过 EventListenerMethodProcessor 处理器解析方法上的 @EventListener 注解

2. 代码

1. MyAnnotationListener
@Component
public class MyAnnotationListener {

	@EventListener(classes = {ApplicationEvent.class})
	public void applicationEventListen(ApplicationEvent event) {
		System.out.println("MyAnnotationListener 接收到事件:" + event.getClass());
	}

}
2. MyApplicationListener
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		System.out.println("MyApplicationListener 接收到事件:" + event.getClass());
	}

}
3. SpringConfig
@Configuration
@ComponentScan
public class SpringConfig {
}
4. EventTest
public class EventTest {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        context.publishEvent(new ApplicationEvent("hello spring annotation") {
        });
        context.close();
        // MyAnnotationListener 接收到事件:class org.springframework.context.event.ContextRefreshedEvent
        // MyApplicationListener 接收到事件:class org.springframework.context.event.ContextRefreshedEvent
        // MyAnnotationListener 接收到事件:class pers.masteryourself.study.spring.framework.event.EventTest$1
        // MyApplicationListener 接收到事件:class pers.masteryourself.study.spring.framework.event.EventTest$1
        // MyAnnotationListener 接收到事件:class org.springframework.context.event.ContextClosedEvent
        // MyApplicationListener 接收到事件:class org.springframework.context.event.ContextClosedEvent
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!