Spring中application*的使用

ApplicationAware

加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的

方法,获得ApplicationContext对象。

前提必须在Spring配置文件中指定该类 

获取context后就可以拿到容器中值

ApplicationEvent

是个抽象类,里面只有一个构造函数和一个长整型的timestamp。

ApplicationListener

是一个接口,里面只有一个onApplicationEvent方法。在使用时 要判断事件

所以自己的类在实现该接口的时候,要实装该方法。

ApplicationContextAware接口可以实现我们在初始化bean的时候给bean注入ApplicationConxt(Spring上下文对象)对象。

ApplicationContextAware接口提供了publishEvent方法,实现了Observe(观察者)设计模式的传播机制,实现了对bean的传播。通过ApplicationContextAware我们可以把系统中所有ApplicationEvent传播给系统中所有的ApplicationListener。因此,我们只需要构造好我们自己的ApplicationEvent和ApplicationListener,就可以在系统中实现相应的监听器。

如果只实现监听,代码会在项目启动后执行。

//实现事件
import org.springframework.context.ApplicationEvent;  
  

public class PersonEvent extends ApplicationEvent {  
    /**  
     * <p>Description:</p>  
     */  
    private static final long serialVersionUID = 1L;  
    public String address;    
    public String text;  
      
    public PersonEvent(Object source) {  
        super(source);  
    }  
      
    public PersonEvent(Object source, String address, String text) {  
        super(source);  
        this.address = address;  
        this.text = text;  
    }  
      
    public void print(){  
        System.out.println("hello spring event!");  
    }  
  
}  
//实现接口监听 注入事件
@Component
import
org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; public class PersonListener implements ApplicationListener { public void onApplicationEvent(ApplicationEvent event) { if(event instanceof EmailEvent){ PersonEvent personEvent= (PersonEvent)event; personEvent.print(); System.out.println("the source is:"+ personEvent.getSource()); System.out.println("the address is:"+ personEvent.address); System.out.println("the email's context is:"+ personEvent.text); } } }
//测试类
import
org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); PersonEvent event = new PersonEvent("hello","test@163.com","this is a email text!"); context.publishEvent(event); } }



原文地址:https://www.cnblogs.com/zyzcj/p/7232200.html