侧边栏壁纸
博主头像
丛庆

没事儿写代码,有事写代码。email:1024@cong.zone

  • 累计撰写 116 篇文章
  • 累计创建 97 个标签
  • 累计收到 4 条评论

【Spring】springboot的发布事件和监听事件

丛庆
2019-12-08 / 0 评论 / 0 点赞 / 674 阅读 / 1,226 字 / 正在检测是否收录...
温馨提示:
部分资料和图片来源于网络,如有危害到您的利益请与我联系删除,1024@cong.zone。

编写SpringApplication,并触发事件

@SpringBootApplication
public class PublishAndListenerApplication {
    public static void main(String[] args) throws IOException {
        ConfigurableApplicationContext context = SpringApplication.run(PublishAndListenerApplication.class, args);
        // 调用注册
        context.getBean(PublishComponent.class).register();
    }
}

事件类
public class RegisteredEvent extends ApplicationEvent {

/**
* 验证码
*/
private String code;

public RegisteredEvent(Object source) {
    super(source);
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

}

事件发布Bean

@Component
public class PublishComponent {

    @Autowired
    private ApplicationContext context;

    public void register() {
        RegisteredEvent registeredEvent = new RegisteredEvent(this);
        registeredEvent.setCode("666");
        System.out.println("需要发送的验证码为->"+ registeredEvent.getCode());
        context.publishEvent(registeredEvent);
        System.out.println("用户注册完成发->布注册完成事件");
    }
}

事件监听

@Component
public class ListenerComponent {

    @EventListener
    public void sentEmail(RegisteredEvent event) {
        System.out.println("邮件发送监听器->监听到注册事件");
        System.out.println("验证码为->"+event.getCode());
        System.out.println("执行->发送注册短信");
    }
}

启动程序

需要发送的验证码为->666
邮件发送监听器->监听到注册事件
验证码为->666
执行->发送注册短信
用户注册完成发->布注册完成事件
0

评论区