当前位置:首页 >> 技术栈专业化分层 >> 【Spring】简化事件的使用,Spring提供了2种使用方式,多普达p860

【Spring】简化事件的使用,Spring提供了2种使用方式,多普达p860

cpugpu芯片开发光刻机 技术栈专业化分层 1
文件名:【Spring】简化事件的使用,Spring提供了2种使用方式,多普达p860 【Spring】简化事件的使用,Spring提供了2种使用方式

Spring中事件可以配置顺序,利用线程池还可以做异步线程通知。怎么样使用事件?Spring简化事件的使用,Spring提供了2种使用方式:面向接口和面向@EventListener注解。

1,面相接口的方式

案例 发布事件

需要先继承ApplicationEventPublisherAware 后发布事件

@Componentpublic class UserRegisterService implements ApplicationEventPublisherAware {private ApplicationEventPublisher applicationEventPublisher;/*** 负责用户注册及发布事件的功能** @param userName 用户名*/public void registerUser(String userName) {//用户注册System.out.println(String.format("用户【%s】注册成功", userName));//发布注册成功事件this.applicationEventPublisher.publishEvent(new UserRegisterEvent(this, userName));}@Overridepublic void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher;}}

然后在监听器中处理业务功能。

监听事件 @Componentpublic class SendEmailListener implements ApplicationListener<UserRegisterEvent> {@Overridepublic void onApplicationEvent(UserRegisterEvent event) {System.out.println(String.format("给用户【%s】发送注册成功邮件!", event.getUserName()));}}

2,面相@EventListener注解的方式 案例用法

直接将这个注解标注在一个bean的方法上,那么这个方法就可以用来处理感兴趣的事件,使用更简单,如下,方法参数类型为事件的类型:

@Componentpublic class UserRegisterListener {@EventListenerpublic void sendMail(UserRegisterEvent event) {System.out.println(String.format("给用户【%s】发送注册成功邮件!", event.getUserName()));}}

协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接