55 lines
1.4 KiB
Java
55 lines
1.4 KiB
Java
|
|
package com.example.demo.event;
|
|||
|
|
|
|||
|
|
import com.example.demo.model.UserEvent;
|
|||
|
|
import org.springframework.context.ApplicationEventPublisher;
|
|||
|
|
import org.springframework.stereotype.Component;
|
|||
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 事件发布器 - 演示如何发布事件
|
|||
|
|
*
|
|||
|
|
* 学习点:
|
|||
|
|
* - ApplicationEventPublisher 接口
|
|||
|
|
* - 依赖注入发布器
|
|||
|
|
* - 解耦:发布者不需要知道监听者
|
|||
|
|
*/
|
|||
|
|
@Component
|
|||
|
|
public class UserEventPublisher {
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private ApplicationEventPublisher eventPublisher;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 发布用户事件
|
|||
|
|
*/
|
|||
|
|
public void publishEvent(UserEvent event) {
|
|||
|
|
System.out.println("[EventPublisher] 发布事件: " + event.getType() + " - " + event.getUserName());
|
|||
|
|
eventPublisher.publishEvent(event);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 便捷方法:发布用户创建事件
|
|||
|
|
*/
|
|||
|
|
public void publishUserCreated(Long userId, String userName) {
|
|||
|
|
UserEvent event = new UserEvent(
|
|||
|
|
UserEvent.Type.CREATED,
|
|||
|
|
userId,
|
|||
|
|
userName,
|
|||
|
|
"新用户注册成功"
|
|||
|
|
);
|
|||
|
|
publishEvent(event);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 便捷方法:发布用户登录事件
|
|||
|
|
*/
|
|||
|
|
public void publishUserLogin(Long userId, String userName) {
|
|||
|
|
UserEvent event = new UserEvent(
|
|||
|
|
UserEvent.Type.LOGIN,
|
|||
|
|
userId,
|
|||
|
|
userName,
|
|||
|
|
"用户登录成功"
|
|||
|
|
);
|
|||
|
|
publishEvent(event);
|
|||
|
|
}
|
|||
|
|
}
|