layout:
title: 7-SpringBoot事件监听
date: 2017-02-07
updated: 2017-02-07
tags:
categories: SpringBoot实战与原理分析
permalink:
thumbnail:
toc: true
comment: true
notag: false
top: false
package com.clsaa.edu.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
@ComponentScan
public class App {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(App.class);
app.addListeners(new MyApplicationLisener());
ConfigurableApplicationContext context = app.run(args);
context.publishEvent(new MyApplicationEvent(new Object()));
context.close();
}
}
package com.clsaa.edu.springboot;
import org.springframework.context.ApplicationEvent;
/**
* Created by Egg on 2017/2/24.
* 定义事件
*/
public class MyApplicationEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param source the object on which the event initially occurred (never {@code null})
*/
public MyApplicationEvent(Object source) {
super(source);
}
}
package com.clsaa.edu.springboot;
import org.springframework.context.ApplicationListener;
/**
* Created by Egg on 2017/2/24.
* 定义事件监听器
*/
public class MyApplicationLisener implements ApplicationListener<MyApplicationEvent> {
@Override
public void onApplicationEvent(MyApplicationEvent event) {
System.out.println("================"+event.getClass());
}
}
package com.clsaa.edu.springboot;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* Created by Egg on 2017/2/24.
*/
@Component
public class MyEventHandler {
@EventListener
public void event(MyApplicationEvent event){
System.out.println("=========="+event.getClass());
}
}