1.背景
观察者模式:当一个对象的状态发生改变的时候,所有依赖于它的对象都会得到通知,比如ApplicationListener
所以,我们可以用这个来做日志,或者其他事情,
2.创建监听器实现ApplicationListener<>接口
package com.example.listener; import com.example.dto.SystemAccessEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class EventListener implements ApplicationListener<SystemAccessEvent> { @Override public void onApplicationEvent(SystemAccessEvent event) { //完成消息接收 System.out.println("Received event: " + event.getMessage()); } }
3.创建被监听的实体类
package com.example.dto; import lombok.Builder; import lombok.Data; import org.springframework.context.ApplicationEvent; @Data @Builder public class SystemAccessEvent extends ApplicationEvent { private String message; public SystemAccessEvent(Object source) { super(source); } }
必须要继承ApplicationEvent类
4.发送事件通知
package com.example; import com.example.dto.SystemAccessEvent; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEventPublisher; @SpringBootTest class ApplicationTests { @Autowired ApplicationEventPublisher eventPublisher; @Autowired ApplicationContext applicationContext; @Test public void publish() { System.out.println("Published message: "); SystemAccessEvent systemAccessEvent = new SystemAccessEvent(this); systemAccessEvent.setMessage("Hello World!"); eventPublisher.publishEvent(systemAccessEvent); } }