Spring @EventListener注解原理
一、测试代码
测试用例
public class SpringEventTest {
@Test
public void test_listener() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
System.out.println("发布事件");
TestEvent event = new TestEvent(new Object(), "事件1");
context.publishEvent(event);
context.close();
}
}
config类
@Configuration
public class EventConfig {
@EventListener
public void listen(TestEvent event) {
System.out.println("接收到事件:" + event);
}
}
TestEvent类
public class TestEvent extends ApplicationEvent {
private String name;
public TestEvent(Object source, String name) {
super(source);
this.name = name;
}
public TestEvent(Object source) {
super(source);
}
@Override
public String toString() {
return "TestEvent{name='" + name + '\'' + '}';
}
}
二、源码
1、容器加载流程
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages)