spring事件发送监听涉及3个部分:事件、发布者和监听者。
1)ApplicationEvent:表示事件本身,自定义事件需要继承该类,可以用来传递数据。
public class TestEvent extends ApplicationEvent {
private String param;
public TestEvent(String param) {
super(param);
this.param = param;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
}
2)ApplicationEventPublisherAware:事件发送器,通过实现这个接口,来触发事件。
@Component
public class TestEventPublisher implements ApplicationEventPublisherAware {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void publishEvent(ApplicationEvent event) {
applicationEventPublisher.publishEvent(event);
}
}
3)ApplicationListener:事件监听器接口,事件的业务逻辑封装在监听器里面。
@Service
public class TestListener implements ApplicationListener<TestEvent> {
@Async // 异步处理
public void onApplicationEvent(TestEvent event) {
System.out.println(".......开始.......");
System.out.println("业务逻辑处理...参数:" + event.getSource());
System.out.println(".......结束.....");
}
}
测试:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({
"classpath*:spring/spring.xml"
})
public class RunEventTest{
@Resource
private TestEventPublisher testEventPublisher;
@Test
public void test() {
testEventPublisher.publishEvent(new TestEvent("abc"));
}
}
参考资料: