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 ApplicationListener<UserRegisterEvent> {@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()));}
}