Spring的事件机制

Spring的事件框架有两个主要成员:

♦ ApplicationEvnet:容器事件,由ApplicationContext发布
♦ ApplicationListener:监听器,可以由容器中的任何监听器Bean担任

 代码实现如下:

pack xx;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class ApplicationEventTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("web/WEB-INF/applicationContext.xml");
TestEvent testEvent = new TestEvent("my test","你好");
     //发布容器事件
applicationContext.publishEvent(testEvent);
}
}


//实现ApplicationListener接口作为监听器,实现onApplicationEvent方法,每当容器内有任何事件触发时,都会触发该方法。
class TestListener implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if(applicationEvent instanceof TestEvent){
TestEvent e = (TestEvent)applicationEvent;
System.out.println(e.getText());
}else {
System.out.println(applicationEvent.getSource());
System.out.println("触发了其他事件!");
}
}
}

//继承ApplicationEvent类,其对象可作为Spring的容器事件
class TestEvent extends ApplicationEvent {
private String text;
public TestEvent(Object source) {
super(source);
}

public TestEvent(Object source, String text) {
super(source);
this.text = text;
}

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}
}

在applicationContext.xml中配置监听器
<beans>
...
<bean class="包名.TestListener">
</beans>

最终运行结果如下:

  org.springframework.context.support.FileSystemXmlApplicationContext@685f4c2e, started on Thu Oct 17 11:32:16 CST 2019
  触发了其他事件!
  你好

  此运行结果说明,监听器不仅监听到程序所触发的事件,还监听了内部发生的事件,因此触发了else{}中的内容



猜你喜欢

转载自www.cnblogs.com/Rando_M/p/11691047.html