spring ApplicationListener接口(续)

之前一篇写了ApplicationListener在spring中的实现

这次写的demo试一下这个接口

先上代码

@Service
public class BeanPostprocessorTest implements BeanPostProcessor, ApplicationListener{
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("++++++++++++++++++++++postProcessAfterInitialization ++++++++++++++++++++++++++");
        System.out.println(beanName);
        return bean;
    }
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // TODO Auto-generated method stub
        return bean;
    }
    
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("++++++++++++++++++++++ApplicationEvent ++++++++++++++++++++++++++");
        System.out.println(event.getClass().getName());
        
    }
}

这个类特别简单,但是同时实现了两个接口

BeanPostProcessor, ApplicationListener

可以只看ApplicationListener的onApplicationEvent

里面可以取到event的实现类

启动spring容器之后可以看到控制台输出了

++++++++++++++++++++++ApplicationEvent ++++++++++++++++++++++++++
org.springframework.context.event.ContextRefreshedEvent
++++++++++++++++++++++ApplicationEvent ++++++++++++++++++++++++++
org.springframework.context.event.ContextStartedEvent

 

也就是说在context refresh 和 start的时候都会执行这个方法

再看一个更实际的例子

dubbo的ServiceBean类同样实现了ApplicationListener这个接口

具体代码如下

public void onApplicationEvent(ApplicationEvent event) {
        if (ContextRefreshedEvent.class.getName().equals(event.getClass().getName())) {
            if (isDelay() && ! isExported() && ! isUnexported()) {
                if (logger.isInfoEnabled()) {
                    logger.info("The service ready on spring started. service: " + getInterface());
                }
                export();
            }
        }
    }

大概意思是当ContextRefreshed时,执行export方法

下一篇说一下BeanPostProcessor这个接口

转载于:https://www.cnblogs.com/liguangming/p/10149096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值