Spring中的ApplicationContext事件机制

时间:2022-06-30 19:38:13

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