事件定义
创建一个自定义事件类 UserLoginEvent
,继承 ApplicationEvent
,用于携带用户登录信息:
import org.springframework.context.ApplicationEvent;public class UserLoginEvent extends ApplicationEvent { //关键点1:extends ApplicationEventprivate String username;public UserLoginEvent(Object source, String username) {super(source);this.username = username;}public String getUsername() {return username;}
}
事件发布
在用户登录逻辑中发布事件,例如在 LoginService
中:
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;@Service
public class LoginService {private final ApplicationEventPublisher eventPublisher;public LoginService(ApplicationEventPublisher eventPublisher) {this.eventPublisher = eventPublisher;}public void login(String username) {// 模拟登录逻辑System.out.println("用户登录成功: " + username);// 关键点2:事件的发布,就一行代码eventPublisher.publishEvent(new UserLoginEvent(this, username));}
}
事件监听
通过 @EventListener
注解实现监听,记录日志:
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;@Component
public class UserLoginEventListener {@EventListenerpublic void handleUserLoginEvent(UserLoginEvent event) {//关键点3:这里意味着监听某个类型的事件System.out.println("[日志] 用户登录事件触发: " + event.getUsername());}
}
测试验证
编写测试类或控制器调用登录方法:
@RestController
public class LoginController {private final LoginService loginService;public LoginController(LoginService loginService) {this.loginService = loginService;}@GetMapping("/login")public String login(@RequestParam String username) {loginService.login(username);return "Login triggered for: " + username;}
}
访问 http://localhost:8080/login?username=testUser
,控制台将输出:
用户登录成功: testUser
[日志] 用户登录事件触发: testUser
关键说明
- 默认同步执行,若需异步处理可在监听方法上添加
@Async
注解