1.核心两个类 以继承 一实现
继承事件类:ApplicationEventc.class
实现监听类:ApplicationListener.class
#2.用法
public class DemoEvent extends ApplicationEvent {
private String message;
public DemoEvent(Demo source,String message) {
super(source);
this.message = message;
}
public Demo getSource() {
return (Demo)source;
}
public String getMessage() {
return message;
}
}
@Component
public class DemoEventListener implements ApplicationListener<DemoEvent> {
@Override
public void onApplicationEvent(DemoEvent event) {
System.out.println("监听到事件:---》"+event.getMessage());
}
}
@Component
public class PublishWay implements ApplicationEventPublisherAware {
public ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
测试:
@SpringBootTest(classes = {TestApplication.class})
public class test {
@Autowired
private ApplicationContext context;
@Autowired
PublishWay publishWay;
@Test
public void testEventPublic(){
Demo demo=new Demo();
demo.setName("hello world");
DemoEvent demoEvent=new DemoEvent(demo,"开始测试");
// 发布事件:方式一
//context.publishEvent(demoEvent);
// 发布事件:方式二
publishWay.applicationEventPublisher.publishEvent(demoEvent);
}
}
扩展点
此为观察者模式,举个原生的spring security用法
感兴趣可以打开源码 研究这个四个类用法 ,
过于简单 就不展示代码了。