1.事件监听
触发某个动作或者事件的代码逻辑
2.Spring中的事件
需要 extends ApplicationEvent
public class AEvent extends ApplicationEvent {
private String name;
private LocalDateTime now;
public AEvent(Object source, String name, LocalDateTime now) {
super(source);
this.name = name;
this.now = now;
}
@Override
public String toString() {
return "AEvent{" +
"name='" + name + '\'' +
", now=" + now +
", source=" + source +
'}';
}
}
#3.spring中的监听
需要 implements ApplicationListener
@Component
public class AEventListener implements ApplicationListener<AEvent> {
@Override
public void onApplicationEvent(AEvent event) {
System.out.println("我是监听类AEventListener,获取到了具体的事件");
System.out.println(event);
}
}
#4.发起(触发)事件
发送者 interface ApplicationEventPublisher
@Service
public class AService {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void sendMessage() {
eventPublisher.publishEvent(new AEvent("我是AEvent","event中的属性", LocalDateTime.now()));
System.out.println("-----+------------------------");
eventPublisher.publishEvent(new BEvent("我是BEvent","event中自定义的属性", LocalDateTime.now()));
}
}
#5.具体的事件执行自己的代码
2022-07-08 18:04:48.843 INFO 42272 --- [nio-9527-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-07-08 18:04:48.844 INFO 42272 --- [nio-9527-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-07-08 18:04:48.844 INFO 42272 --- [nio-9527-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
我是监听类AEventListener,获取到了具体的事件
AEvent{name='event中的属性', now=2022-07-08T18:04:48.863897500, source=我是AEvent}
-----+------------------------
我是监听类BEventListener,获取到了具体的事件
AEvent{name='event中自定义的属性', now=2022-07-08T18:04:48.867889700, source=我是BEvent}