zoukankan      html  css  js  c++  java
  • 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这个接口

  • 相关阅读:
    HDU 6191 Query on A Tree ( 2017广西邀请赛 && 可持久化Trie )
    BZOJ 4318 OSU! ( 期望DP )
    洛谷 P2473 [SCOI2008]奖励关 ( 期望DP )
    Codeforces #499 E Border ( 裴蜀定理 )
    HDU 6444 Neko's loop ( 2018 CCPC 网络赛 && 裴蜀定理 && 线段树 )
    HDU 6438 Buy and Resell ( 2018 CCPC 网络赛 && 贪心 )
    Nowcoder Hash Function ( 拓扑排序 && 线段树优化建图 )
    Nowcoder Playing Games ( FWT 优化 DP && 博弈论 && 线性基)
    js中的深拷贝与浅拷贝
    nrm 源管理器
  • 原文地址:https://www.cnblogs.com/liguangming/p/10149096.html
Copyright © 2011-2022 走看看