Spring中的ApplicationContext事件机制

Posted work hard work smart

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring中的ApplicationContext事件机制相关的知识,希望对你有一定的参考价值。

ApplicationContext的事件机制是观察者设计模式的实现,通过ApplicationEvent类和ApplicationListerner接口来实现。

1. 创建EmailEvent

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;
    }

}

2. 创建EmailNotifier类

public class EmailNotifier implements ApplicationListener{

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof EmailEvent) {
            EmailEvent emailEvent = (EmailEvent)event;
            System.out.println("邮件接收地址:" + emailEvent.getAddress());
            System.out.println("邮件正文: " + emailEvent.getText());
        }
        
    }

}

 

3. 创建容器配置文件  beans_mail.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="emailNotifier" class="com.tutorialspoint.EmailNotifier">
   </bean>
   
   
</beans>

 

4. 测试

ApplicationContext context = new ClassPathXmlApplicationContext("beans_mail.xml");
EmailEvent emailEvent = new EmailEvent("hello","[email protected]","this is test");
context.publishEvent(emailEvent);

 

5. 输出结果

六月 01, 2016 5:13:10 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org[email protected]9b6220: startup date [Wed Jun 01 17:13:10 CST 2016]; root of context hierarchy
六月 01, 2016 5:13:10 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans_mail.xml]
邮件接收地址:[email protected]163.com
邮件正文: this is test

 

以上是关于Spring中的ApplicationContext事件机制的主要内容,如果未能解决你的问题,请参考以下文章

ApplicationContex是干啥的

有WebService的项目中写applicationContex.xml文件时应注意!!!

Spring简答题

Spring之Aware

IOC与DI(xml 配置)

spring Bean