标签:ntp efault info 相关 att tcl mes 调用 元素
一、简介
spring事件是观察者设计模式的实现,主要有三个元素:
简单示例:
自定义事件
public class TestEvent extends ApplicationEvent { private String message; public TestEvent(Object source) { this(source, "default message"); } public TestEvent(Object source, String msg) { super(source); this.message = msg; } public String getMessage() { return message; } }
监听者
@Component public class TestListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof TestEvent) { System.out.println(((TestEvent)event).getMessage()); } } }
XML配置
<context:component-scan base-package="cn.matt.event"/>
测试
public class EventTest { @Test public void testCustomEvent() { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml"); context.publishEvent(new TestEvent("", "hello matt")); } }
补充:
定义监听者时,可通过泛型指定监听事件类型,因此,上例监听者可定义如下:
@Component public class TestListener implements ApplicationListener<TestEvent> { @Override public void onApplicationEvent(TestEvent event) { System.out.println(((TestEvent) event).getMessage()); } }
二、spring容器事件
spring为容器启动各阶段定义了相关事件,实现如图:
事件说明:
使用示例
@Component public class ApplicationStartUpListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("spring context inited"); } }
标签:ntp efault info 相关 att tcl mes 调用 元素
原文地址:https://www.cnblogs.com/MattCheng/p/9046980.html