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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值