码迷,mamicode.com
首页 > 移动开发 > 详细

Spring中的ApplicationContext事件机制

时间:2016-06-01 18:04:55      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

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","spring@163.com","this is test");
context.publishEvent(emailEvent);

 

5. 输出结果

六月 01, 2016 5:13:10 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@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]
邮件接收地址:spring@163.com
邮件正文: this is test

 

Spring中的ApplicationContext事件机制

标签:

原文地址:http://www.cnblogs.com/linlf03/p/5550386.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!