ref属性和idref属性都是可以用在constructor-arg元素和property元素中注入的。但是它们之间的注入还是有点区别的。
首先看一下spring官方给出的文档和说明:
ref:官方的说明:The above bean definition snippet is exactly equivalent (at runtime) to the following snippet(大概意思:这两个片段配置是等价的在运行的时候)
<bean id="theTargetBean" class="..." />
<bean id="client" class="...">
<property name="targetName" value="theTargetBean" />
</bean>
idref:官方给出的说明:The idref element is simply an error-proof way to pass the id (string value - not a reference) of another bean in the container to a or element.(通过或者注入bean的时候通过idref来检查注入的bean是否在容器中的一种检查错误的方式)。
<bean id="theTargetBean" class="..."/>
<bean id="theClientBean" class="...">
<property name="targetName">
<idref bean="theTargetBean" />
</property>
</bean>
那么这两个标签的区别是什么呢?
实际上,idref注入的只是目标bean的id,而不是目标bean的实例,同时使用idref容器在部署的时候还会验证这个名称是否存在,就相当于是一个验证功能。
其实idref就跟value差不多,<value>用来给property或者constructor-arg一个String类型的值,而idref虽然也是给他们一个String类型的值,但这个值必须是容器中存在的bean的id.
而ref用来干什么的呢?
同样在<constructor-arg/>或者<property/>元素内部也可以使用ref元素。用来将bean中指定属性的值设置为对容器中的另外一个bean的引用。ref元素有三个属性,区别如下:
1、local 只能指定与当前配置的Bean在同一个配置文件中的Bean定义的名称;
2、parent 只能指定位于当前容器的父容器中定义的对象引用;
3、bean 基本上都行,即以上两种情况都可以,所以,在这个情况下,直接使用bean来指定对象引用就可以了。