前言
前面讲到了SpringBoot 七个生命周期回调事件函数,SpringBoot底层是在jdk中的java.util.EventObject
类和java.util.EventListener
之上封装实现的发布订阅机制。同时也提供了自定义事件定义,该种方式是一种设计模式–观察者设计模式,优势在于解耦,模块和模块耦合度降低方便扩展。
如下实现一个需求:注册用户,然后插入到数据库,另外还需要给用户发邮件和短信。
编码
1.创建用户注册事件基类
import org.springframework.context.ApplicationEvent;
/**
* 用户注册事件
* @author terry
* @version 1.0
* @date 2022/6/8 15:37
*/
public class UserRegisterEvent extends ApplicationEvent {
/**
* 用户名
*/
private String name;
public UserRegisterEvent(Object source) {
super(source);
}
public UserRegisterEvent(Object source, String name) {
super(source);
this.name = name;
}
public String getUserName() {
return name;
}
}
2.用户注册,发布事件例子。
import lombok.extern.java.Log;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
@Service
@Log
public class UserService implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void register(String userName) {
log.info("用户注册" + userName + ", 数据插入到数据库!");
// 发布用户注册事件
applicationEventPublisher.publishEvent(new UserRegisterEvent(this, userName));
}
}
3.发送短信,订阅事件例子。
import lombok.extern.java.Log;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
/**
* 短信service
* @author terry
* @version 1.0
* @date 2022/6/8 15:43
*/
@Service
@Log
public class SmsService implements ApplicationListener<UserRegisterEvent> {
@Override
public void onApplicationEvent(UserRegisterEvent event) {
log.info("发送短信给用户:" + event.getUserName());
}
}
4.发送邮件,订阅事件例子。
import lombok.extern.java.Log;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
/**
* 邮件service
* @author terry
* @version 1.0
* @date 2022/6/8 15:43
*/
@Service
@Log
public class EmailService implements ApplicationListener<UserRegisterEvent> {
@Override
public void onApplicationEvent(UserRegisterEvent event) {
log.info("发送邮件给用户:" + event.getUserName());
}
}
5.测试类,模拟用户注册。
import org.springframework.context.ApplicationEvent;
/**
* 用户注册事件
* @author terry
* @version 1.0
* @date 2022/6/8 15:37
*/
public class UserRegisterEvent extends ApplicationEvent {
/**
* 用户名
*/
private String name;
public UserRegisterEvent(Object source) {
super(source);
}
public UserRegisterEvent(Object source, String name) {
super(source);
this.name = name;
}
public String getUserName() {
return name;
}
}
打印如下:
2022-06-08 15:49:48.196 INFO 27560 --- [ main] com.terry.event.event.UserService : 用户注册terry, 数据插入到数据库!
2022-06-08 15:49:48.197 INFO 27560 --- [ main] com.terry.event.event.EmailService : 发送邮件给用户:terry
2022-06-08 15:49:48.198 INFO 27560 --- [ main] com.terry.event.event.SmsService : 发送短信给用户:terry