@Override
public void audit(RealAuth realAuth) {
RealAuth old=realauthMapper.selectByPrimaryKey(realAuth.getId());
Userinfo applier=userinfoService.get(old.getApplier().getId());
if(old!=null && RealAuth.STATE_NORMAL==old.getState()) {
if(!applier.getIsRealAuth() && realAuth.getId().equals(applier.getRealAuthId())) {
old.setRemark(realAuth.getRemark());
old.setAuditor(UserContext.getCurrent());
old.setAuditTime(new Date());
old.setState(realAuth.getState());
realauthMapper.updateByPrimaryKey(old);
if(RealAuth.STATE_AUDIT==realAuth.getState()) {
// 修改成功实名认证成功
applier.addState(BitStatesUtils.OP_REAL_AUTH);
// 实名认证成功后,发送短信
// 实名认证成功后,发送邮件
}else {
applier.setRealAuthId(null);
}
userinfoService.update(applier);
}
}
}
上面的代码,需要在实名认证成功后发送短信和邮件。但这些事情并不属于实名认证的事情,而且后续需求可能更改,不止需要发短信和邮件可能还要做一些别的事情,一旦需求更改,这里的代码也要更改。所以尽量将实名认证后需要做的事情和实名认证本身解耦
利用spring的事件监听
1、创建消息对象
@Getter
public class RealAuthSuccessEvent extends ApplicationEvent {
private RealAuth realAuth;
public RealAuthSuccessEvent(Object source, RealAuth realAuth) {
super(source);
this.realAuth = realAuth;
}
}
2、创建监听器
@Service
public class SmsServiceImpl implements ISmsService ,ApplicationListener<RealAuthSuccessEvent>{
@Override
public void onApplicationEvent(RealAuthSuccessEvent event) {
this.realAuthSendSms(event.getRealAuth());
}
private void realAuthSendSms(RealAuth realAuth) {
System.out.println(realAuth.getApplier().getUsername()+"实名认证成功");
}
}
3、发布消息
@Autowired
private ApplicationContext ctx;
@Override
public void audit(RealAuth realAuth) {
RealAuth old=realauthMapper.selectByPrimaryKey(realAuth.getId());
Userinfo applier=userinfoService.get(old.getApplier().getId());
if(old!=null && RealAuth.STATE_NORMAL==old.getState()) {
if(!applier.getIsRealAuth() && realAuth.getId().equals(applier.getRealAuthId())) {
old.setRemark(realAuth.getRemark());
old.setAuditor(UserContext.getCurrent());
old.setAuditTime(new Date());
old.setState(realAuth.getState());
realauthMapper.updateByPrimaryKey(old);
if(RealAuth.STATE_AUDIT==realAuth.getState()) {
// 修改成功实名认证成功
applier.addState(BitStatesUtils.OP_REAL_AUTH);
// 实名认证成功后,发布消息
ctx.publishEvent(new RealAuthSuccessEvent(this, realAuth));
}else {
applier.setRealAuthId(null);
}
userinfoService.update(applier);
}
}
}
4、如果需要监听多个消息对象
@Service
public class SmsServiceImpl implements ISmsService ,ApplicationListener<ApplicationEvent>{
@Override
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof RealAuthSuccessEvent) {
RealAuthSuccessEvent e = (RealAuthSuccessEvent) event;
this.realAuthSendSms(e.getRealAuth());
}
}
private void realAuthSendSms(RealAuth realAuth) {
System.out.println(realAuth.getApplier().getUsername()+"实名认证成功");
}
}