springboot监听事件实现
1.定义listener
/**
- @author wangLi
- @date 2023-09-22 14:09
*/
@Component
@Slf4j
public class MyListenerTest implements ApplicationListener {
@Override
public void onApplicationEvent(TestEvent testEvent) {
log.info(“進入事件監聽機制開始”);
String msg = testEvent.getMsg();
log.info(“進入事件監聽機制結束 msg:{}”,msg);
}
}
2.定义event
![在这里插入图片描述](https://img-blog.csdnimg.cn/087e41d9c5c54845bd04cd967691f039.png
/**
- @author wangLi
- @date 2023-09-22 14:16
*/
@Setter
@Getter
public class TestEvent extends ApplicationEvent {
public TestEvent(Object source) {
super(source);
}
private String msg;
}
3.使用的地方发布event
@Component
public class TestServiceImpl implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void test() {
TestEvent testEvent = new TestEvent(this);
testEvent.setMsg("dddddd");
applicationEventPublisher.publishEvent(testEvent);
}
}