实现监听方式三步骤:
1.自定义事件一般继承ApplicationEvent
2.定义事件监听实现ApplicationContextListener
3.发布事件
第一种:添加监听器
首先自定义事件
package com.gcx.spring.springboot;
import org.springframework.context.ApplicationEvent;
public class MyApplicationEvent extends ApplicationEvent {
private static final long serialVersionUID = 1L;
public MyApplicationEvent(Object source) {
super(source);
// TODO Auto-generated constructor stub
}
/**
*
*/
}
接着定义事件监听
package com.gcx.spring.springboot;
import org.springframework.context.ApplicationListener;
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent>{
@Override
public void onApplicationEvent(MyApplicationEvent event) {
System.out.println("事件监听后:"+event.getClass());
}
}
package com.gcx.spring.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
/**
* Hello world!
*
*/
@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();
}
}
第二种:Spring容器管理
在MyApplicationContextListener上交给Spring容器管理,并且在测试类中去掉添加监听
第三种:application.properties中 添加 context.listener.classes = 定义事件监听的类,这个属性在DelegatingApplicationListener中
第四种:使用EventListener注解用在方法上,切该类交给spring容器管理
package com.gcx.spring.springboot;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class MyEventHande {
@EventListener
public void eventHande(ApplicationEvent e){
System.out.println("事件监听后的结果"+e.getClass());
}
}