现在的位置: 首页 > 数据库 > 正文

spring加载bean实例化顺序

2020年02月12日 数据库 ⁄ 共 2152字 ⁄ 字号 评论关闭

问题来源:

有一个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   的执行顺序。

Java代码  

  1. public class A implements InitializingBean {  
  2.   
  3.  private B b;  
  4.  private String name; // = b.funb();  
  5.   
  6.  public void setB(B b) {  
  7.   System.out.println("A.setB initialed");  
  8.   this.b = b;  
  9.  }  
  10.   
  11.  public A() {  
  12.   System.out.println("A initialed");  
  13.  }  
  14.   
  15.  public void init() {  
  16.   System.out.println("init");  
  17.   this.name = b.funb();  
  18.  }  
  19.   
  20.  @Override  
  21.  public String toString() {  
  22.   return super.toString() + this.name;  
  23.  }  
  24.   
  25.  public void afterPropertiesSet() throws Exception {  
  26.   
  27.   //其实放在这里也可以  
  28.   
  29.   //this.name = b.funb();  
  30.   System.out.println("afterPropertiesSet");  
  31.   
  32.  }  
  33.   
  34. }  
  35.   
  36. public class B {  
  37.   
  38.  public String funb() {  
  39.   System.out.println("funb");  
  40.   return "B.funb";  
  41.  }  
  42.   
  43.  public B() {  
  44.   System.out.println("B initialed");  
  45.  }  
  46. }  

 

spring配置文件

<beans default-autowire="byName">      <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 initialedB initialedA.setB initialedafterPropertiesSetinitfunbtestspring.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加载bean实例化顺序的相关介绍,要了解更多php教程_php自学_php视频教程下载 - 绵阳技术博客内容请登录学步园。

抱歉!评论已关闭.