Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ref vs idref attributes in spring bean declaration

Tags:

spring

Can someone tell me the difference between

<bean id="b1" class="" />

<bean id="" class="">
 <property name="b1" ref="b1" />
</bean>

and

<bean id="" class="">
 <property name="b1" idref="b1" />
</bean>

and which one has to be used when?

like image 506
Maniganda Prakash Avatar asked Nov 20 '09 01:11

Maniganda Prakash


People also ask

What is ref attribute in spring?

Spring ref attribute The ref attribute is a shortcut to the <ref> tag, used to refer to other beans for injection.

What is ref in bean?

If you are referring to a bean in different XML file, you can reference it with a ' ref ' tag, ' bean ' attribute. <ref bean="someBean"/> In this example, the bean “OutputHelper” declared in ' Spring-Common. xml ' can access to other beans in ' Spring-Output.

What is the advantage of using Idref tag?

The advantage of using idref over value attribute is that if there will be no bean with that id, it will throw error at runtime. The idref allows validating the existence of bean with that id at deployment time. The idref is used with <constructor-arg/> or <property/> element.

How do I use Idref?

idref is used to pass the name (identifier) of a bean (that is, a String). <idref bean="pointA"> is exactly the same as just the string value pointA , except that Spring will complain if such a bean is not defined.


2 Answers

Here is a little more verbose example, suppose you have two beans A and B:

<bean class="A" id="a" />

<bean class="B"/>
    <constructor-arg>
        <ref bean="a"/>
        <idref bean="a"/>
    </constructor-arg>
</bean>

In this case B would have a constructor that would look like this:

public B(A a, String string) {
     string.equals("a"); //true
}

So with ref you can reference an object and with idref you just reference the name of the bean

like image 197
lanoxx Avatar answered Oct 31 '22 20:10

lanoxx


ref is used to pass the bean that the ref refers to.
idref is used to pass the name of the bean (as a String) that is referred to.

http://forum.springsource.org/showthread.php?t=74355

like image 27
Kaleb Brasee Avatar answered Oct 31 '22 19:10

Kaleb Brasee