定义事件
public class UserModifyEvent extends ApplicationEvent { private static final long serialVersionUID = 1L; private User user; //是新增 private boolean isInsert; //是修改 private boolean isUpdate; //是删除 private boolean isDelete; public UserModifyEvent(User user, SqlCommandType sqlCommandType) { super(user); this.user = user; this.areaId = UserUtils.getLoginAreaId(); this.isInsert = SqlCommandType.INSERT.equals(sqlCommandType); this.isUpdate = SqlCommandType.UPDATE.equals(sqlCommandType); this.isDelete = SqlCommandType.DELETE.equals(sqlCommandType); } public User getUser() { return user; } public boolean isInsert() { return isInsert; } public boolean isUpdate() { return isUpdate; } public boolean isDelete() { return isDelete; } }
发布事件
@Autowired ApplicationEventPublisher publisher; public JsonResult saveUser(User user){ try{ userDao.insertSelective(user); publisher.publishEvent(new UserModifyEvent(user, SqlCommandType.INSERT)); catch(DuplicateKeyException e){ userDao.updateSelective(user); publisher.publishEvent(new UserModifyEvent(user, SqlCommandType.UPDATE)); }catch(Exception e){ log.error(e); throw new LocalException("保存用户失败"); } return OK(user.getId()); }
同步到华为云视频帐号:
public class SameUser2HuaWei implements ApplicationListener<UserModifyEvent> { @Override public void onApplicationEvent(UserModifyEvent event) { User user = event.getUser(); ...... } }
给用户发送短信消息提醒
public class SendNoticeWhenCreateUser implements ApplicationListener<UserModifyEvent> { @Override public void onApplicationEvent(UserModifyEvent event) { User user = event.getUser(); ...... } }
给用户给用户初始化一些最小权限
public class InitMiniAuthWhenInsertUser implements ApplicationListener<UserModifyEvent> { @Override public void onApplicationEvent(UserModifyEvent event) { User user = event.getUser(); ...... } }
给用户关连一些系统必要的设置
public class JoinSettingWhenCreateUser implements ApplicationListener<UserModifyEvent> { @Override public void onApplicationEvent(UserModifyEvent event) { User user = event.getUser(); ...... } }