目录
自定义事件
事件监听器
事件发布者(服务层)
使用示例controller层
Spring源码分析之事件机制——观察者模式(一)-CSDN博客
Spring源码分析之事件机制——观察者模式(二)-CSDN博客
这两篇文章是这个篇章的前篇,感兴趣的读者可以阅读一下,从spring源码分析观察者模式
接下来说明一下Spring事件机制使用案例,就一个模拟用户注册场景的场景吧,事件机制其实还可以运用到更加广泛的作用。
说实话,个人感觉Spring事件机制真的好用。
自定义事件
public class UserRegisteredEvent extends ApplicationEvent {private final String username;private final String email;private final LocalDateTime registeredTime;public UserRegisteredEvent(Object source, String username, String email) {super(source);this.username = username;this.email = email;this.registeredTime = LocalDateTime.now();}// getter方法public String getUsername() {return username;}public String getEmail() {return email;}public LocalDateTime getRegisteredTime() {return registeredTime;}
}
事件监听器
@Component
@Order(1) // 定义监听器执行顺序
public class EmailNotificationListener implements ApplicationListener<UserRegisteredEvent> {private final EmailService emailService;@Autowiredpublic EmailNotificationListener(EmailService emailService) {this.emailService = emailService;}@Overridepublic void onApplicationEvent(UserRegisteredEvent event) {// 发送欢迎邮件emailService.sendWelcomeEmail(event.getEmail(), event.getUsername());log.info("Welcome email sent to user: {}", event.getUsername());}
}
@Component
@Order(2)
public class UserCacheListener implements ApplicationListener<UserRegisteredEvent> {private final CacheManager cacheManager;@Autowiredpublic UserCacheListener(CacheManager cacheManager) {this.cacheManager = cacheManager;}@Overridepublic void onApplicationEvent(UserRegisteredEvent event) {// 更新用户缓存cacheManager.putUserCache(event.getUsername());log.info("User cache updated for: {}", event.getUsername());}
}
事件发布者(服务层)
@Service
@Transactional
public class UserService {private final UserRepository userRepository;private final ApplicationEventPublisher eventPublisher;@Autowiredpublic UserService(UserRepository userRepository, ApplicationEventPublisher eventPublisher) {this.userRepository = userRepository;this.eventPublisher = eventPublisher;}public User registerUser(String username, String email, String password) {// 验证用户数据validateUserData(username, email, password);// 创建用户User user = new User(username, email, password);user = userRepository.save(user);// 发布用户注册事件eventPublisher.publishEvent(new UserRegisteredEvent(this, username, email));log.info("User registered and event published: {}", username);return user;}private void validateUserData(String username, String email, String password) {// 数据验证逻辑}
}
使用示例controller层
@RestController
@RequestMapping("/api/users")
public class UserController {private final UserService userService;@Autowiredpublic UserController(UserService userService) {this.userService = userService;}@PostMapping("/register")public ResponseEntity<UserDTO> registerUser(@RequestBody UserRegistrationRequest request) {User user = userService.registerUser(request.getUsername(),request.getEmail(),request.getPassword());return ResponseEntity.ok(UserDTO.fromUser(user));}
}
用户注册时,UserService发布UserRegisteredEvent事件,EmailNotificationListener同步处理邮件发送,UserCacheListener同步更新缓存,AsyncAnalyticsListener异步处理统计数据,通过@Order注解控制监听器执行顺序。
这种实现方式将用户注册的核心逻辑与后续的处理操作解耦,使得系统更容易维护和扩展。每个监听器都专注于自己的职责,可以独立地添加、移除或修改,而不会影响其他部分的代码。