Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding spring bin name "&myBean"

Tags:

java

spring

In one spring context I found that some bean references contains & before bean name. I wonder what & in the begin of spring name means.

like image 555
user590444 Avatar asked Feb 16 '23 09:02

user590444


1 Answers

They are references to FactoryBeans (i.e. to the factories themselves, as opposed to the objects that the factories produce). From the Spring documentation

When you need to ask a container for an actual FactoryBean instance itself, not the bean it produces, you preface the bean id with the ampersand symbol & (without quotes) when calling the getBean() method of the ApplicationContext. So for a given FactoryBean with an id of myBean, invoking getBean("myBean") on the container returns the product of the FactoryBean, and invoking getBean("&myBean") returns the FactoryBean instance itself.

Ampersands in XML need to be escaped as & entity references, so if you wanted to declare a property value in XML which is a reference to a FactoryBean you'd need

<property name="someProperty" ref="&amp;myBean" />
like image 182
Ian Roberts Avatar answered Feb 26 '23 19:02

Ian Roberts