SpringBoot 有序事件监听器
实现
SmartApplicationListener
重写supportsEventType、supportsSourceType来区分是否是我们监听的事件,只有两个方法同时返回true时才会执行,getOrder这个方法可以解决执行监听的顺序问题,return的数值越小证明优先级越高,执行顺序越靠前。
用户注册发送邮件
首先创建一个事件,监听都是围绕着事件
import com.base.client.model.vo.UserVO;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
/**
* 用户创建事件
*
* @author arjun
* @date 2020/12/09
*/
@Getter
public class UserRegisterEvent extends ApplicationEvent {
/**
* 发送的内容
*/
private UserVO content;
/**
* 重写构造器
*
* @param source 发送事件的对象
* @param content 发送的内容
*/
public UserRegisterEvent(Object source, UserVO content) {
super(source);
this.content = content;
}
}
创建UserService
只用于实现注册事件发布功能(当然业务逻辑也是可以写,这里只为测试)
这里注入 ApplicationEventPublisher
接口
import com.base.client.model.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
/**
* @author arjun
* @date 2020/12/09
*/
@Service
public class UserService {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void register(UserVO vo) {
System.out.println("----------------发布注册事件----------------------");
// 发布 UserRegisterEvent 事件
eventPublisher.publishEvent(new UserRegisterEvent(this, vo));
}
}
ApplicationEvent
监听所有事件发布,SmartApplicationListener
接口添加了两个方法supportsEventType
、supportsSourceType
来区分是否是我们监听的事件,只有两个方法同时返回true时才会执行onApplicationEvent
,getOrder
这个方法可以解决执行监听的顺序问题,return的数值越小证明优先级越高,执行顺序越靠前。
import com.base.client.model.vo.UserVO;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;
/**
* @author arjun
* @date 2020/12/09
*/
@Component
public class UserRegisterListener implements SmartApplicationListener {
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
return aClass == UserRegisterEvent.class;
}
@Override
public boolean supportsSourceType(Class<?