Spring中ApplicationListener简单的使用讲解

Spring中ApplicationListener简单的使用讲解

背景
ApplicationListener是Spring事件机制的一部分,与抽象类ApplicationEvent类配合来完成ApplicationContext的事件机制。

一.原理讲解

如果容器中存在ApplicationListener的Bean,当ApplicationContext调用publishEvent方法时,对应的Bean会被触发。这一过程是典型的观察者模式的实现。
ApplicationListener源码

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

	/**
	 * Handle an application event.
	 * @param event the event to respond to
	 */
	void onApplicationEvent(E event);

}

ContextRefreshedEvent事件的监听
以Spring的内置事件ContextRefreshedEvent为例,当ApplicationContext被初始化或刷新时,会触发ContextRefreshedEvent事件,下面我们就实现一个ApplicationListener来监听此事件的发生。

@Component // 需对该类进行Bean的实例化
public class LearnListener implements ApplicationListener<ContextRefreshedEvent> {
   @Override
   public void onApplicationEvent(ContextRefreshedEvent event) {
      // 打印容器中出事Bean的数量
      System.out.println("监听器获得容器中初始化Bean数量:" + event.getApplicationContext().getBeanDefinitionCount());
   }
}

如上,便完成了一个事件监听类的实现和实例化。

二.自定义监听器、事件、发布事件

1.自定义事件

public class NotifyEvent extends ApplicationEvent {


	private String email;

	private String content;

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

	public NotifyEvent(Object source, String email, String content) {
		super(source);
		this.email = email;
		this.content = content;
	}
    // 省略getter/setter方法
}

2.自定义监听器

@Component
public class NotifyListener implements ApplicationListener<NotifyEvent> {

	@Override
	public void onApplicationEvent(NotifyEvent event) {
		System.out.println("邮件地址:" + event.getEmail());
		System.out.println("邮件内容:" + event.getContent());
	}
}

监听器通过@Component注解进行实例化,并在onApplicationEvent中打印相关信息。

3.单元测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ListenerTest {

	@Autowired
	private WebApplicationContext webApplicationContext;

	@Test
	public void testListener() {

		NotifyEvent event = new NotifyEvent("object", "abc@qq.com", "This is the content");

		webApplicationContext.publishEvent(event);//发布一个自定义事假,当事件发布后,会被相应的springApplicationListener监听到执行重写的 onApplicationEvent逻辑;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值