码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot事件监听

时间:2018-10-18 23:59:51      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:override   事件监听   打印   print   技术分享   bubuko   nap   source   ide   

技术分享图片

代码演示:

技术分享图片

package com.boot.event.eventdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class EventDemoApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(EventDemoApplication.class);
        //第一种方式 添加监听事件
        // app.addListeners(new MyApplicationListener());
        ConfigurableApplicationContext context = app.run(args);
        // 发布事件
        context.publishEvent(new MyApplicationEvent(new Object()));

        context.close();
    }
}
package com.boot.event.eventdemo;

import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class HandlerEvent {
//第四种方式,最常用方式    
    @EventListener(MyApplicationEvent.class)
    public void handlerEvent(MyApplicationEvent event) {
        System.out.println("接受到了事件====:"+event.getClass());
        System.out.println("接受到了事件====:"+event.getSource());
    }

    @EventListener(ContextClosedEvent.class)
    public void handlerEvent1(Object event) {
        System.out.println("接受到了事件:"+event.getClass());
    }
}
package com.boot.event.eventdemo;

import org.springframework.context.ApplicationEvent;

public class MyApplicationEvent extends ApplicationEvent {
    public MyApplicationEvent(Object source) {
        super(source);
    }
}
package com.boot.event.eventdemo;

import org.springframework.context.ApplicationListener;

//第二种方式 @Component
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {

    @Override
    public void onApplicationEvent(MyApplicationEvent event) {
        System.out.println("接受到了事件:"+event.getClass());
        System.out.println("接受到了事件:"+event.getSource());
    }
}

application.properties

#第三种方式 
context.listener.classes=com.boot.event.eventdemo.MyApplicationListener

使用第四种方式配置监听器的打印结果:

技术分享图片

 

SpringBoot事件监听

标签:override   事件监听   打印   print   技术分享   bubuko   nap   source   ide   

原文地址:https://www.cnblogs.com/lm970585581/p/9813651.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!