Springboot 事件监听


实现监听方式三步骤:

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());
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值