Spring中的事件監聽實現


在spring中我們可以自定義事件,並且可以使用ApplicationContext類型對象(就是spring容器container)來發布這個事件
事件發布之后,所有的ApplicaitonListener(監聽器)實例都會被觸發並調用指定方法onApplicationEvent()來處理.

這里的ApplicationEvent繼承於Java中的EventObject,隸屬於事件對象

ApplicaitonListener繼承於Java中的EventListener,隸屬於監聽者對象

例如:
自定義事件類RainEvent:

public class RainEvent extends ApplicationEvent {
public RainEvent(Object source) {
super(source);
}
}

監聽器類RainListener1

public class RainListener1 implements ApplicationListener<RainEvent>{

@Override
public void onApplicationEvent(RainEvent event) {
System.out.println("唐僧大喊:" + event.getSource() + "趕快收衣服嘍!");
}

}

監聽器類RainListener2

public class RainListener2 implements ApplicationListener<RainEvent>{

public void onApplicationEvent(RainEvent event) {
System.out.println("我們:" + event.getSource() + "太好了不用上課了!");
}
}

xml文件:

<!-- 只需要把這倆個監聽器類交給spring容器管理就可以了 -->
<bean class="com.briup.ioc.event.RainListener1"></bean>
<bean class="com.briup.ioc.event.RainListener2"></bean>

測試:

main:
String path = "com/briup/ioc/event/event.xml";
ApplicationContext container = new ClassPathXmlApplicationContext(path);
//發布事件
container.publishEvent(new RainEvent("下雨了!"));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM