在spring容器中注册过的类中,不能出现AppContext.getBean的原因

问题描述

在代码中,取得一个在 spring 容器中注册的类有两种方法:

1) AppContext.getBean

2) applicationContext-Service.xml 中配置好类之间引用关系,在对应的类代码中加入 getset 方法。

如果在 spring 容器中注册过的类中,出现 AppContext.getBean 的代码,例如:

public class Fsj1{

         public Fsj1(){

                   System.out.println("111");

         }

}

public class Fsj2 {

         Fsj1 fsj1 = (Fsj1) AppContext.getBean("service1");

         public Fsj2(){

                   System.out.println("222");

         }

}

applicationContext-service.xml 中配置如下:

<bean id="service1" class="cn.ac.iscas.share.cus.service.Fsj1"/>

<bean id="service2" class="cn.ac.iscas.share.cus.service.Fsj2"/>

那么在程序启动的时候就会 报错:

    java.lang.NullPointerException

         at cn.ac.intec.entity.orm.AppContext.getBean(AppContext.java:146)

问题分析

      我们来看一下 AppContext 类代码:

public class AppContext{

        private static BeanFactory factory = null;

public static Object getBean(String name)  {

             return factory.getBean(name);

         }

}

空指针的错误正是由于 factorynull 引起的,这是因为在程序启动时, BeanFactory 尚未对所有的对象创建完毕,也就是说 factory 实例还没有初始化完毕。在这个过程中又去调用 factory.getBean 当然会出现空指针错误。

当程序启动完毕后, factory 就初始化完毕了,这时候在程序的运行中(最常见的就是在 action 中)调用 AppContext.getBean 就不会出错了。

 

问题解决

对于两个都在 spring 中注册的类,互相之间的依赖关系应该在配置文件中写好,即使是循环依赖, spring 也可以很好的解决这个问题。例如:

public class Fsj1 {

         Fsj2 service2;

         public Fsj1(){

                   System.out.println("111");

         }

         public Fsj2 getService2() {

                   return service2;

         }

         public void setService2(Fsj2 service2) {

                   this. service2= service2;

         }

}

public class Fsj2 {

         Fsj1 service1;

         public Fsj2(){

                   System.out.println("222");

         }

         public Fsj1 getService1() {

                   return service1;

         }

         public void setService1(Fsj1 service1) {

                   this.service1 = service1;

         }

}

applicationContext-service.xml 中配置如下:

<bean id="service1" class="cn.ac.iscas.share.cus.service.Fsj1">

        <property name="service2" ref="service2" />

  </bean>

<bean id="service2" class="cn.ac.iscas.share.cus.service.Fsj2">

         <property name="service1" ref="service1" />

</bean>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值