什么是ApplicationContext?
它是spring的核心,Context我們通常解釋為上下文環境,但是理解成容器會更好些。
ApplicationContext則是應用的容器。
Spring把Bean(object)放在容器中,需要用就通過get方法取出來。
ApplicationEvent
是個抽象類,里面只有一個構造函數和一個長整型的timestamp。
ApplicationListener
是一個接口,里面只有一個onApplicationEvent方法。
所以自己的類在實現該接口的時候,要實裝該方法。
如果在上下文中部署一個實現了ApplicationListener接口的bean,
那么每當在一個ApplicationEvent發布到 ApplicationContext時,
這個bean得到通知。其實這就是標准的Oberver設計模式。
下面給出例子:
首先創建一個ApplicationEvent實現類:
1 package com.spring.event; 2 3 import org.springframework.context.ApplicationEvent; 4 5 public class EmailEvent extends ApplicationEvent { 6 /** 7 * <p>Description:</p> 8 */ 9 private static final long serialVersionUID = 1L; 10 public String address; 11 public String text; 12 13 public EmailEvent(Object source) { 14 super(source); 15 } 16 17 public EmailEvent(Object source, String address, String text) { 18 super(source); 19 this.address = address; 20 this.text = text; 21 } 22 23 public void print(){ 24 System.out.println("hello spring event!"); 25 } 26 27 }
給出監聽器:
1 package com.spring.event; 2 3 import org.springframework.context.ApplicationEvent; 4 import org.springframework.context.ApplicationListener; 5 public class EmailListener implements ApplicationListener { 6 7 public void onApplicationEvent(ApplicationEvent event) { 8 if(event instanceof EmailEvent){ 9 EmailEvent emailEvent = (EmailEvent)event; 10 emailEvent.print(); 11 System.out.println("the source is:"+emailEvent.getSource()); 12 System.out.println("the address is:"+emailEvent.address); 13 System.out.println("the email's context is:"+emailEvent.text); 14 } 15 16 } 17 18 }
applicationContext.xml文件配置:
<bean id="emailListener" class="com.spring.event.EmailListener"></bean>
測試類:
1 package com.spring.event; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class Test { 7 public static void main(String[] args) { 8 ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); 9 10 //HelloBean hello = (HelloBean) context.getBean("helloBean"); 11 //hello.setApplicationContext(context); 12 EmailEvent event = new EmailEvent("hello","boylmx@163.com","this is a email text!"); 13 context.publishEvent(event); 14 //System.out.println(); 15 } 16 }
測試結果
hello spring event! the source is:hello the address is:boylmx@163.com the email's context is:this is a email text!
