ApplicationContext的事件機制是觀察者模式的實現,經過ApplicationEvent類和ApplicationListener接口,能夠實現ApplicationConext的事件處理。若是容器中有一個ApplicationListener Bean,每當ApplicationContext發佈ApplicationEven時,ApplicationListener Bean將自動被觸發。java
Spring的事件框架有以下兩個成員:spring
1)ApplicationEvent:容器事件,必須由ApplicationContext發佈。app
2)ApplicationListener:監聽器,可由容器中的任何監聽器承擔。框架
Spring的事件機制與全部事件機制都基本類似,它們都須要事件源、事件和事件監聽器組成。此處的事件源是ApplicationConetext,而且事件必須由Java程序顯示觸發。ide
onApplicationEvent(ApplictionEvent event);每當容器內發送任何事件時,此方法都被觸發;this
下面定義一個郵件事件:code
package com.custle.spring; import org.springframework.context.ApplicationEvent; public class EmailEvent extends ApplicationEvent { private String address; private String text; public EmailEvent(Object source) { super(source); } public EmailEvent(Object source, String address, String text) { super(source); this.address = address; this.text = text; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
package com.custle.spring; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; public class EmailNotifiter implements ApplicationListener { //該方法會在容器發送時自動觸發 @Override public void onApplicationEvent(ApplicationEvent event) { if(event instanceof EmailEvent){ //只處理EmailEvent,發送email通知 EmailEvent emailEvent = (EmailEvent)event; System.out.println("須要發送郵件的接收地址:"+emailEvent.getAddress()); }else{ //容器內置事件不做處理 System.out.println("容器自己的事件: "+ event); } } }
在applicationContext-spring.xml中配置郵件事件:xml
<!-- 配置郵件監聽器 --> <bean id="emailNotifiter" class="com.custle.spring.EmailNotifiter" />
經過ClassPathXmlApplicationContext讀取配置文件:接口
package com.custle.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class EmailTest { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext-spring.xml"); EmailEvent emailEvent = new EmailEvent("hello", "526295149@qq.com", "send email"); //將EmailEvent事件添加至ApplicationContext容器 applicationContext.publishEvent(emailEvent); } }
控制檯輸出:事件
2018-02-05 13:24:27 INFO (AbstractApplicationContext.java:513) - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@22f4bf02: startup date [Mon Feb 05 13:24:27 CST 2018]; root of context hierarchy 2018-02-05 13:24:27 INFO (XmlBeanDefinitionReader.java:316) - Loading XML bean definitions from class path resource [applicationContext-spring.xml] 容器自己的事件: org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@22f4bf02: startup date [Mon Feb 05 13:24:27 CST 2018]; root of context hierarchy] 須要發送郵件的接收地址:526295149@qq.com
上文是經過ApplicationContext的pulishEvent()來主動觸發容器事件,其實當系統建立Spring容器、加載Spring容器時也會自動觸發容器事件。