用户注册发布用户注册事件
用户实体类定义
@Data
public class User {
/** 用户名 */
private String username;
/** 密码 */
private String password;
/** 昵称 */
private String nickname;
/** 头像 */
private String headUrl;
/** 性别 */
private String gender;
}
用户注册事件定义
public class UserRegisterEvent extends ApplicationEvent {
private User user;
public UserRegisterEvent(Object source, User user) {
super(source);
this.user = user;
}
public User getUser() {
return user;
}
}
事件监听器定义
@Component
public class UserRegisterEventListener implements ApplicationListener<UserRegisterEvent> {
public void onApplicationEvent(UserRegisterEvent userRegisterEvent) {
User user = userRegisterEvent.getUser();
System.out.println("新注册用户" + JSON.toJSONString(user));
}
}
发布事件方式一:
@Service
public class UserService {
@Autowired
private ApplicationContext context;
/** 用户注册 */
public boolean userRegister(User user) {
// 添加到数据库操作
// 发布用户注册事件
System.out.println("Spring容器方式发布");
context.publishEvent(new UserRegisterEvent(this, user));
return true;
}
}
发布事件方式2
@Service
public class UserService2 implements ApplicationEventPublisherAware {
private ApplicationEventPublisher eventPublisher;
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.eventPublisher = applicationEventPublisher;
}
/** 用户注册 */
public boolean userRegister(User user) {
// 添加到数据库操作
// 发布用户注册事件
System.out.println("Spring Aware方式发布");
eventPublisher.publishEvent(new UserRegisterEvent(this, user));
return true;
}
}
配置类
@Configuration
@ComponentScan("com.zhun")
public class EventConfig {
}
测试类
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
User user = new User();
user.setUsername("admin");
user.setPassword("123456");
user.setNickname("管理员");
user.setGender("1");
UserService userService = context.getBean(UserService.class);
userService.userRegister(user);
UserService2 userService2 = context.getBean(UserService2.class);
userService2.userRegister(user);
}
}
日志输出