SpringBoot-事件驱动开发
在事件驱动开发中,需要有三种对象
- 事件本身
- 事件发布
- 事件订阅
事件
public class LoginSuccessEvent implement ApplicationEvent {
LoginSuccessEvent(String params) {
super(params);
}
}
事件发布
@Component
public class EventPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
public void sendEvent(ApplicationEvent event) {
applicationEventPublisher.publishEvent(event);
}
// 在应用启动时会自动执行该方法,对字段进行注入
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
事件订阅两种实现
@Service
public class PersonService implements ApplicationListener<LoginSuccessEvent> {
public void loginUser(String username) {
System.out.println(username);
}
@Override
public void onApplicationEvent(LoginSuccessEvent event) {
UserEntity source = (UserEntity) event.getSource();
loginUser(source.getUsername());
}
}
@Service
public class GoodsService {
@EventListener
public void sendGoods(LoginSuccessEvent loginSuccessEvent) {
UserEntity source = (UserEntity) loginSuccessEvent.getSource();
System.out.println(source.getUsername());
}
}

浙公网安备 33010602011771号