调用Spring

时间:2017-08-01 06:22:14

标签: java spring dependency-injection sequence init

我正在使用Spring DI版本4.2。 我的" applicationContext.xml"内容如下。

   <bean id="bObj1" class="com.springExample.B" scope="prototype" init-method="init" destroy-method="destory" />

以下是我的课程&#34; com.springExample.B&#34;

public class B  implements BeanPostProcessor {


public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("In class B, Method postProcessBeforeInitialization()");
    return bean;
}

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("In class B, Method postProcessAfterInitialization()");
    return bean;
}

public void init() {
    System.out.println("In class B, Method init()");
}

public void m3() {
    System.out.println("In class B, Method m3()");

}   

public void destory() {
    System.out.println("In class B, Method  destory()");
}

}

我已经阅读了生命周期方法的调用顺序如下。

  1. postProcessBeforeInitialization()
  2. 的init()
  3. postProcessAfterInitialization()
  4. 我正在创建spring容器并按如下方式调用Bean

    ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");    
    B b = ac.getBean("bObj1", B.class);
    b.m3(); 
    

    我已经在Class&#34; com.springExample.B&#34;的所有方法中编写了SOP语句。当我运行代码时,我得到如下输出。

    In class B, Method init()
    In class B, Method postProcessBeforeInitialization()
    In class B, Method init()
    In class B, Method postProcessAfterInitialization()
    In class B, Method m3()
    

    我无法理解为什么在postProcessBeforeInitialization()之前调用init()方法?

1 个答案:

答案 0 :(得分:0)

实现BeanPostProcessor的单独类时。 它按预期工作。
下面是更新的课程和新课程。

public class B  {

public void init() {
    System.out.println("In class B, Method init()");
}

public void m3() {
    System.out.println("In class B, Method m3()");
}

public void destory() {
    System.out.println("In class B, Method  destory()");
}
}

BeanPostProcessorImpl类

public class BeanPostProcessorImpl implements BeanPostProcessor {

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("In class BeanPostProcessorImpl, Method postProcessBeforeInitialization()");
    return bean;
}

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    System.out.println("In class BeanPostProcessorImpl, Method postProcessAfterInitialization()");
    return bean;
}
}