SpringBoot-事件驱动开发

在事件驱动开发中,需要有三种对象

  1. 事件本身
  2. 事件发布
  3. 事件订阅

事件

prismjs
public class LoginSuccessEvent implement ApplicationEvent {
	LoginSuccessEvent(String params) {
		super(params);
	}
}

事件发布

prismjs
@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;
    }
}

事件订阅两种实现

prismjs
@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());
    }
}

prismjs
@Service
public class GoodsService {

    @EventListener
    public void sendGoods(LoginSuccessEvent loginSuccessEvent) {
        UserEntity source = (UserEntity) loginSuccessEvent.getSource();
        System.out.println(source.getUsername());
    }
}
posted @   wzpro  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示