What can be the use case for Spring bean idref?

100 views Asked by At

I know that idref is used to pass the id of a bean (i.e String value but not the reference). I was asked in an interview, what can be the use case of idref? Why and when it should be used?

1

There are 1 answers

2
ItachiUchiha On BEST ANSWER

idref just adds a layer of security by validating at deployment time that the referenced, named bean actually exists.

A very nice example with appropriate explanation is provided in this link

Example

<bean id="abc" class="..."/>

<bean id="xyz" class="...">
  <property name="abcName">
      <idref bean="abc" />
  </property>
</bean>

can also be written as

<bean id="abc" class="..." />

<bean id="xyz" class="...">
  <property name="abcName" value="abc" />
</bean>

The advantage of using first way is already described.

If you use the second method then no validation is performed on the value that is passed to the abcName property of the xyz bean i.e. during the loading of the context.

Errors are only discovered when the xyz bean is instantiated. So, we can never know if any typos have been injected by the developer during the instantiation phase.

Note : It is just a recommended approach, not a mandatory approach