需求
當用戶注冊后,給他發送一封郵件通知他注冊成功了,然后給他初始化積分,再發放一張新用戶注冊優惠券等。
用戶注冊事件
public class UserRegisterEvent extends ApplicationEvent{ public UserRegisterEvent(String name) { //name即source 復雜的對象,但注意要了解清楚序列化機制 super(name); } }
用戶注冊服務發布者
@Service public class UserService { @Autowired private ApplicationEventPublisher applicationEventPublisher; public void register(String name) { System.out.println("用戶:" + name + " 已注冊!"); applicationEventPublisher.publishEvent(new UserRegisterEvent(name)); } }
注意:再Spring中,服務必須交給 Spring 容器托管。ApplicationEventPublisherAware 是由 Spring 提供的用於為 Service 注入 ApplicationEventPublisher 事件發布器的接口,使用這個接口,我們自己的 Service 就擁有了發布事件的能力。用戶注冊后,不再是顯示調用其他的業務 Service,而是發布一個用戶注冊事件。
創建事件訂閱者(郵件服務、積分服務等)
方式一:
@Service //一定要加入容器 public class EmailService implements ApplicationListener<UserRegisterEvent> { @Override public void onApplicationEvent(UserRegisterEvent userRegisterEvent) { System.out.println("郵件服務接到通知,給 " + userRegisterEvent.getSource() + " 發送郵件..."); } }
方式二(注解):
@Service //一定要加入容器 public class EmailService { @EventListener(classes = {UserRegisterEvent.class}) public void listen(UserRegisterEvent event) { System.out.println("注解監聽器:" + event.getClass().getName()); } }
注意:事件訂閱者的服務同樣需要托管於 Spring 容器,ApplicationListener接口是由 Spring 提供的事件訂閱者必須實現的接口,我們一般把該 Service 關心的事件類型作為泛型傳入。處理事件,通過 event.getSource() 即可拿到事件的具體內容,在本例中便是用戶的姓名。
SpringBoot 測試啟動類
@SpringBootApplication @RestController public class EventDemoApp { public static void main(String[] args) { SpringApplication.run(EventDemoApp.class, args); } @Autowired UserService userService; @RequestMapping("/register") public String register(){ userService.register("zhangsan"); return "success"; } }
轉自:https://www.littleteacher.cn/archives/spring-zhong-de-shi-jian-ji-zhi-applicationeventpublishe