Spring 中的事件機制 ApplicationEventPublisher


轉自:https://www.littleteacher.cn/archives/spring-zhong-de-shi-jian-ji-zhi-applicationeventpublishe

需求

當用戶注冊后,給他發送一封郵件通知他注冊成功了,然后給他初始化積分,再發放一張新用戶注冊優惠券等。

用戶注冊事件

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() + " 發送郵件...");
    }
}

注意:事件訂閱者的服務同樣需要托管於 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";
    }
}

完成

至此, 完成需求,后期無論如何擴展,我們只需要添加相應的事件訂閱者即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM