Spring Boot(十一) 事件监听

1.事件流程


    1.自定义事件,一般是继承ApplicationEvent抽象类
    2.定义事件监听器,一般是实现ApplicationListener接口
       启动时,需要把监听器加入到Spring容器中
    4.发布事件,使用 ApplicationEventPublisher.publishEvent 发布事件

 2.配置监听器 4种方法


    1.SpringApplication.addListeners 添加监听器

        如

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication app=new SpringApplication(App.class);
        app.addListeners(new MyApplicationListener());
        ConfigurableApplicationContext context=app.run(args);
        context.publishEvent(new MyApplicationEvent(new Object()));
        context.close();
    }
}


    2.把监听器纳入到Spring容器中管理
        (如使用 @Component 注解)

    3.使用context.listener.classes 配置项配置 (详细内容 参照 DelegatingApplicationListener)
        在 application.properties 配置文件中 添加 context.listener.classes=监听类的全局名称 
        (如 context.listener.classes=com.edu.spring.springboot.SpringBoot11.MyApplicationListener)

   4.使用 @EventListener注解,在方法上面加入@EventListener注解,且改类要纳入到Spring容器中(详细内容 参照 EventListenerMethodProcessor, EventListenerFactory)
        如


@Component
public class MyEventHandle {
    /**
     * 参数任意
     * 所有,该参数事件,或者其子事件(子类)都可以接受到
     */
    @EventListener
    public void event(Object event) {
        System.out.println("接收到事件:"+event.getClass());
        
    } 
}

 3.Demo 中用到的类 

    1.MyApplicationEvent

/**
 * 定义事件
 * @author LiuZJ
 * @date 2018年8月4日 上午12:12:17
 */
public class MyApplicationEvent extends ApplicationEvent {

	private static final long serialVersionUID = 1L;

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

}

    2.MyApplicationListener

/**
 * 定义事件监听器
 * @author LiuZJ
 * @date 2018年8月4日 上午12:21:17
 */
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {

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

}

    3.MyEventHandle

@Component
public class MyEventHandle {
	/**
	 * 参数任意
	 * 所有,该参数事件,或者其子事件(子类)都可以接受到
	 */
	@EventListener
	public void event(Object event) {
		System.out.println("接收到事件:"+event.getClass());
		
	} 
}

    4.App

@SpringBootApplication
public class App {
	public static void main(String[] args) {
		SpringApplication app=new SpringApplication(App.class);
//		app.addListeners(new MyApplicationListener());
		ConfigurableApplicationContext context=app.run(args);
		context.publishEvent(new MyApplicationEvent(new Object()));
		context.close();
	}
}

猜你喜欢

转载自blog.csdn.net/lzj470612639/article/details/81396657