14
votes

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?

4

4 Answers

13
votes

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

11
votes

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

2
votes

idref must point to a real bean. and the format should be <idref bean=""/>

0
votes

id is used to create an instance of Class, idref is used for pointing to name of the bean