依赖检查

依赖检查

Spring除了能对容器中bean的依赖设置进行检查外,还可以检查bean定义中实际属性值的设置,当然也包括采用自动装配方式设置属性值的检查。

当需要确保bean的所有属性值(或者属性类型)被正确设置的时候,那么这个功能会非常有用。当然,在很多情况下,bean类的某些属性会具有默认值,或者有些属性并不会在所有场景下使用,因此这项功能会存在一定的局限性。就像自动装配一样,依赖检查也可以针对每一个bean进行设置。依赖检查默认为not,它有几种不同的使用模式,在xml配置文件中,可以在bean定义中为dependency-check属性使用以下几种值:

模式

说明

none

没有依赖检查,如果bean的属性没有值的话可以不用设置。

simple

对于原始类型及集合(除协作者外的一切东西)执行依赖检查

objects

仅对协作者执行依赖检查

all

对协作者,原始类型及集合执行依赖检查

 

下面还是通过示例来演示

程序清单:EmpServiceImpl.java

public class EmpServiceImpl {

   private String name;

   private Integer age;

   private List<Emp> list;

   public void setName(String name) {

      this.name = name;

   }

   public void setList(List<Emp> list) {

      this.list = list;

   }

}

 

程序清单:测试类àEmpTest.java

public class EmpTest {

   @Test

   public void test1(){

      ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

      EmpServiceImpl esi=(EmpServiceImpl) ac.getBean("empServiceImpl");

   }

}

 

applicationContext.xml文件

第一种:

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"  ></bean>

解析:上述文件不会出现任何错误。即使在EmpServiceImpl.java中存在属性 及其相应的set依赖注入方法。

 

第二种:

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"  dependency-check="none"></bean>

解析:和第一种一样!

 

第三种:

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"  dependency-check="simple"></bean>

解析:会报如下错误:

 

Error creating bean with name 'empServiceImpl' defined in class path resource [applicationContext.xml] :Unsatisfied dependency expressed through bean property 'name':Set this property value or disable dependency checking for this bean.

也就是说因为empServiceImpl中有name这个属性,及其相应的set依赖注入方法。又因在配置文件中有依赖检查dependency-check。也许有人会问为什么错误信息中没有age属性和list集合呢?这是因为dependency-check的值为"simple”,这个值只依赖检查原始数据,例如:StringInteger···,没有包含age属性是因为其没有相应的set依赖注入方法。

解决方案:

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"  dependency-check="simple">

      <property name="name">

        <value>Well_Being</value>

      </property>

   </bean>

第四种:

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"  dependency-check="objects"></bean>

解析:会报如下错误:

Error creating bean with name 'empServiceImpl' defined in class path resource [applicationContext.xml] :Unsatisfied dependency expressed through bean property 'list':Set this property value or disable dependency checking for this bean.

不难发现,错误的矛头又指向了list集合。objects”,这个值只依赖检查bean和集合

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值