Spring学习笔记 关于spring 2.x中dependency-check标签与Spring3中的实现方式

来源:互联网 发布:php exec 返回值 编辑:程序博客网 时间:2024/05/01 14:10


在Bean被创建时Bean的属性(property)如果在配置文件Bean的定义中没有进行初始化赋值,默认情况下Spring对于没有进行初始化的属性(property)是不做检查的。但是很多情况下会要求Bean特定的属性必须进行初始化赋值,在Spring2.x中通过在bean标签中使用dependency-check属性设定由Spring进行强制检查的方式。denpendency-check属性有四个值

 

<bean id="ernie" class="com.***." dependency-check="none">//如果不进行设置设就是Spring中dependency-check的默认值,不进行任何检查。


<bean id="ernie" class="com.***." dependency-check="simple">//只检查简单类型属性以及集合类型属性

<bean id="ernie" class="com.***." dependency-check="object">//检查除简单类型属性以及集合类型属性外的引用类型属性
<bean id="ernie" class="com.***." dependency-check="all">//检查所有类型属性


当检查没有通过时会抛出org.springframework.beans.factory.UnsatisfiedDependencyException异常。

看了以上的教程那会儿我就跑到自己的工程上写代码测试下。结果抛出了以下异常

Attribute 'dependency-check' is not allowed to appear in element 'bean'

我的spring-config.xml代码如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">    <bean id="toBeCheckedBean" class="dependencycheck.ToBeCheckedBean" dependency-check="simple" />    </beans>

 

上网查了下资料发现,在我上边代码中使用了spring3.0的xsd(http://www.springframework.org/schema/beans/spring-beans-3.0.xsd)(用来验证xml文档有效性,同DTD文件作用相同),而在spring3.0的xsd文件中根本没有dependency-check属性的定义,原因是在spring3+中已经放弃使用这个属性了,如果需要使用这个属性则需要使用spring2.5的xsd文件。

而既然Spring3中放弃使用了dependency-check属性一定就会有替代它的功能出现。

查了下资料,果然,在spring3中替代dependency-check有4条建议:

  • Use constructors (constructor injection instead of setter injection) exclusively to ensure the right properties are set.
  • 使用构造方法(使用构造方法注入替代setter注入)专门用来确认特定属性被初始化
  • Create setters with a dedicated init method implemented.
  • 用init方法初始化setter的属性
  • Create setters with @Required annotation when the property is required.
  • 在需要强制进行初始化的setters上标注@Required,可以参考http://www.mkyong.com/spring/spring-dependency-checking-with-required-annotation/
  • Use @Autowired-driven injection which also implies a required property by default.
  • 使用@Autowired-driven 注入也可以实现

 

原创粉丝点击