spring 事件发布与监听
📅 2026/7/13 4:56:11
👁️ 阅读次数
📝 编程学习
1、定义发布事件的消息体,实现ApplicationEvent接口
public class BlackListEvent extends ApplicationEvent{private String address;private String title;public StringgetAddress(){returnaddress;}public StringgetTitle(){returntitle;}public BlackListEvent(Object source, String address, String title){super(source);this.address=address;this.title=title;}}2、在业务代码中 通过ApplicationEventPublisher对象的publishEvent方法来发布事件,一般先实现ApplicationEventPublisherAware接口注入ApplicationEventPublisher对象
public class TestServiceImpl implements ITestService, ApplicationEventPublisherAware{private ApplicationEventPublisher applicationEventPublisher;@Override public Stringhelloword(){//发送事件 applicationEventPublisher.publishEvent(new BlackListEvent(this,"aaa","bbb"));return"helloword";}@Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher){this.applicationEventPublisher=applicationEventPublisher;}}3、定义监听器,实现ApplicationListener接口
@Component public class BlackListNotifier implements ApplicationListener<BlackListEvent>{@Override public void onApplicationEvent(BlackListEvent event){System.out.println("监听事件");System.out.println(event.getAddress());System.out.println(event.getTitle());}}
编程学习
技术分享
实战经验