浙江平安建设信息系统网站,上海有名的设计工作室,wordpress发布时间精确到秒,模板背景图片Spring中事件可以配置顺序#xff0c;利用线程池还可以做异步线程通知。怎么样使用事件#xff1f;Spring简化事件的使用#xff0c;Spring提供了2种使用方式#xff1a;面向接口和面向EventListener注解。 1,面相接口的方式
案例
发布事件
需要先继承ApplicationEventP… Spring中事件可以配置顺序利用线程池还可以做异步线程通知。怎么样使用事件Spring简化事件的使用Spring提供了2种使用方式面向接口和面向EventListener注解。 1,面相接口的方式
案例
发布事件
需要先继承ApplicationEventPublisherAware 后发布事件 Component
public 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;}
}
然后在监听器中处理业务功能。
监听事件 Component
public class SendEmailListener implements ApplicationListenerUserRegisterEvent {Overridepublic void onApplicationEvent(UserRegisterEvent event) {System.out.println(String.format(给用户【%s】发送注册成功邮件!, event.getUserName()));}
} 2,面相EventListener注解的方式
案例用法
直接将这个注解标注在一个bean的方法上那么这个方法就可以用来处理感兴趣的事件使用更简单如下方法参数类型为事件的类型
Component
public class UserRegisterListener {EventListenerpublic void sendMail(UserRegisterEvent event) {System.out.println(String.format(给用户【%s】发送注册成功邮件!, event.getUserName()));}
}