zoukankan      html  css  js  c++  java
  • spring加载bean实例化顺序

    转载:http://blog.sina.com.cn/s/blog_525960510100ipwj.html

      http://blog.sina.com.cn/s/blog_6940cab30102uwma.html

    问题来源:

    有一个bean为 A,一个bean为B。想要A在容器实例化的时候的一个属性name赋值为B的一个方法funB的返回值。

    如果只是在A里单纯的写着:

    private B b;
    private String name = b.funb();

    会报错说nullpointException,因为这个时候b还没被set进来,所以为null。

    解决办法为如下代码,同时学习下spring中 InitializingBean ,对象 构造方法 , init-method 的执行顺序。

    public class A implements InitializingBean {

     private B b;
     private String name; // = b.funb();

     public void setB(B b) {
        System.out.println("A.setB initialed");
        this.b = b;
     }

     public A() {
        System.out.println("A initialed");
     }

     public void init() {
        System.out.println("init");
        this.name = b.funb();
     }

     @Override
     public String toString() {
        return super.toString() + this.name;
     }

     public void afterPropertiesSet() throws Exception {

        //其实放在这里也可以

         //this.name = b.funb();
        System.out.println("afterPropertiesSet");

     }

    }

    public class B {

     public String funb() {
        System.out.println("funb");
        return "B.funb";
     }

     public B() {
        System.out.println("B initialed");
     }
    }

    spring配置文件

    <beans default->
          <bean id="a" class="testspring.A" init-method="init">
          </bean>
          <bean id="b" class="testspring.B">
          </bean>
     </beans>

    测试代码:

     public static void main(String[] args) {
          ApplicationContext context = new FileSystemXmlApplicationContext(
              "src/testspring/bean.xml");
          A a = (A) context.getBean("a");
          System.out.println(a);

     }

    程序输出为:

    A initialed
    B initialed
    A.setB initialed
    afterPropertiesSet
    init
    funb
    testspring.A@50d89cB.funb

    从这里看到A的name属性在bean加载完成的时候也被成功设置为B的funB方法的返回值了,要点就是用init-method来实现。

    加载顺序也可以看到为:

    先构造函数——>然后是b的set方法注入—— >InitializingBean 的afterPropertiesSet方法——>init- method方法

    总结为:

    以下内容是从书中摘录 来的,但是我发现即使摘录一遍,对其内容的理解也会更加深入!
    一、Spring装配Bean的过程
    1. 实例化;
    2. 设置属性值;
    3. 如果实现了BeanNameAware接口,调用setBeanName设置Bean的ID或者Name;
    4. 如果实现BeanFactoryAware接口,调用setBeanFactory 设置BeanFactory;
    5. 如果实现ApplicationContextAware,调用setApplicationContext设置ApplicationContext
    6. 调用BeanPostProcessor的预先初始化方法;
    7. 调用InitializingBean的afterPropertiesSet()方法;
    8. 调用定制init-method方法;
    9. 调用BeanPostProcessor的后初始化方法;


    Spring容器关闭过程
    1. 调用DisposableBean的destroy();
    2. 调用定制的destroy-method方法;

    ==========================

    spring InitializingBean init-method postConstruct  执行顺序:

    Spring 容器中的 Bean 是有生命周期的,Spring 允许在 Bean 在初始化完成后以及 Bean 销毁前执行特定的操作,常用的设定方式有以下三种:
     
    通过实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;
    通过 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法;
    在指定方法上加上@PostConstruct 或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用。 
    这是我们就有个疑问,这三种方式是完全等同的吗,孰先孰后?
     
    下面我们将带着这个疑问,试图通过测试代码以及分析Spring源码找到答案。
     
    首先,我们还是编写一个简单的测试代码:
     
    Java代码 复制代码 收藏代码
    public class InitSequenceBean implements InitializingBean {   
        
        public InitSequenceBean() {   
           System.out.println("InitSequenceBean: constructor");   
        }   
          
        @PostConstruct  
        public void postConstruct() {   
           System.out.println("InitSequenceBean: postConstruct");   
        }   
          
        public void initMethod() {   
           System.out.println("InitSequenceBean: init-method");   
        }   
          
        @Override  
        public void afterPropertiesSet() throws Exception {   
           System.out.println("InitSequenceBean: afterPropertiesSet");   
        }   
    }  
      
     
    并且在配置文件中添加如下Bean定义:
     
     
     
     
    好了,我们启动Spring容器,观察输出结果,就可知道三者的先后顺序了:
     
    InitSequenceBean: constructor
     
    InitSequenceBean: postConstruct
     
    InitSequenceBean: afterPropertiesSet
     
    InitSequenceBean: init-method
     
    通过上述输出结果,三者的先后顺序也就一目了然了:
     
    Constructor > @PostConstruct > InitializingBean > init-method
     
    先大致分析下为什么会出现这些的结果:构造器(Constructor)被率先调用毋庸置疑,InitializingBean先于init-method我们也可以理解(在也谈Spring容器的生命周期中已经讨论过),但是PostConstruct为何率先于InitializingBean执行呢?
     
    我们再次带着这个疑问去查看Spring源代码来一探究竟。
    通过Debug并查看调用栈,我们发现了这个类org.springframework.context.annotation.CommonAnnotationBeanPostProcessor,从命名上,我们就可以得到某些信息——这是一个BeanPostProcessor。想到了什么?在也谈Spring容器的生命周期中,我们提到过BeanPostProcessor的postProcessBeforeInitialization是在Bean生命周期中afterPropertiesSet和init-method之前执被调用的。
     
    再次观察CommonAnnotationBeanPostProcessor这个类,它继承自InitDestroyAnnotationBeanPostProcessor。InitDestroyAnnotationBeanPostProcessor顾名思义,就是在Bean初始化和销毁的时候所作的一个前置/后置处理器。
     
    通过查看InitDestroyAnnotationBeanPostProcessor类下的postProcessBeforeInitialization方法:
     
    Java代码 复制代码 收藏代码
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {   
           LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());   
           try {   
               metadata.invokeInitMethods(bean, beanName);   
           }   
           catch (InvocationTargetException ex) {   
               throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());   
           }   
           catch (Throwable ex) {   
               throw new BeanCreationException(beanName, "Couldn't invoke init method", ex);   
           }   
            return bean;   
        }  
      
     
    查看findLifecycleMetadata方法,继而我们跟踪到buildLifecycleMetadata这个方法体中,看下buildLifecycleMetadata这个方法体的内容:
     
    Java代码 复制代码 收藏代码
    private LifecycleMetadata buildLifecycleMetadata(final Class clazz) {   
           final LifecycleMetadata newMetadata = new LifecycleMetadata();   
           final boolean debug = logger.isDebugEnabled();   
           ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {   
               public void doWith(Method method) {   
                  if (initAnnotationType != null) {   
                      if (method.getAnnotation(initAnnotationType) != null) {   
                         newMetadata.addInitMethod(method);   
                         if (debug) {   
                             logger.debug("Found init method on class [" + clazz.getName() + "]: " + method);   
                         }   
                      }   
                  }   
                  if (destroyAnnotationType != null) {   
                      if (method.getAnnotation(destroyAnnotationType) != null) {   
                         newMetadata.addDestroyMethod(method);   
                         if (debug) {   
                             logger.debug("Found destroy method on class [" + clazz.getName() + "]: " + method);   
                         }   
                      }   
                  }   
               }   
           });   
           return newMetadata;   
    }  
     
    分析这段代码发现,在这里会去判断某方法有没有被initAnnotationType/destroyAnnotationType注释,如果有,则添加到init/destroy队列中,后续一一执行。
     
    initAnnotationType/destroyAnnotationType注释是什么呢,我们在CommonAnnotationBeanPostProcessor的构造函数中看到下面这段代码:
     
    Java代码 复制代码 收藏代码
    public CommonAnnotationBeanPostProcessor() {   
           setOrder(Ordered.LOWEST_PRECEDENCE - 3);   
           setInitAnnotationType(PostConstruct.class);   
           setDestroyAnnotationType(PreDestroy.class);   
           ignoreResourceType("javax.xml.ws.WebServiceContext");   
    }  
      
     
    一切都清晰了吧。一言以蔽之,@PostConstruct注解后的方法在BeanPostProcessor前置处理器中就被执行了,所以当然要先于InitializingBean和init-method执行了。
     
    最后,给出本文的结论,Bean在实例化的过程中:
     
    Constructor > @PostConstruct > InitializingBean > init-method
  • 相关阅读:
    Vmware 虚拟硬盘 合并多个分割文件
    一步步带你做vue后台管理框架(三)——登录功能
    一步步带你做vue后台管理框架(二)——上手使用
    webpack教程(六)——分离组件代码
    webpack教程(五)——图片的加载
    webpack教程(四)——css的加载
    input输入框自动填充黄色背景解决方案
    webpack教程(三)——热刷新
    webpack教程(二)——webpack.config.js文件
    webpack教程(一)——初体验
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/5886050.html
Copyright © 2011-2022 走看看