依赖检查
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”,这个值只依赖检查原始数据,例如:String、Integer···,没有包含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和集合