简单实用SpringApplicationListener
Posted ITdfq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单实用SpringApplicationListener相关的知识,希望对你有一定的参考价值。
编写测试事件
package com.itdfq.springlistener.event;
import org.springframework.context.ApplicationEvent;
/**
* @Author: GodChin
* @Date: 2021/8/12 9:55
* @Blog: http://itdfq.com
* @QQ: 909256107
* @Description:
*/
public class TestEvent extends ApplicationEvent {
private String name;
public TestEvent(Integer source, String name) {
super(source);
this.name = name;
}
public String getName() {
return name;
}
}
编写对应的监听器
package com.itdfq.springlistener.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @Author: GodChin
* @Date: 2021/8/12 9:56
* @Description:
*/
@Component
public class TestEventHandler implements ApplicationListener<TestEvent> {
@Override
public void onApplicationEvent(TestEvent testEvent) {
System.out.println("处理器执行了");
System.out.println(testEvent);
System.out.println(testEvent.getName());
System.out.println(testEvent.getSource());
}
}
测试
package com.itdfq.springlistener;
import com.itdfq.springlistener.event.TestEvent;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationEventPublisher;
import javax.annotation.Resource;
@SpringBootTest
class SpringListenerApplicationTests {
//使用spring自带的事件发布
@Resource
private ApplicationEventPublisher eventPublisher;
@Test
void contextLoads() {
eventPublisher.publishEvent(new TestEvent(123,"李白"));
}
}
结果
以上是关于简单实用SpringApplicationListener的主要内容,如果未能解决你的问题,请参考以下文章