简体   繁体   中英

Must a Spring bean represent a unique object?

Can Spring bean be a reference to another bean? It doesn't seem to work:

<bean id="player1" class="some.package.Player" />
<bean id="player2" ref="player1" />

If this is possible, is it useful? So far, I was thinking that every bean must represent a unique object, but some idea came to my head: what if I had a Singleton class called eg Sun with a "public static Sun getInstance()" method and I would make two beans being the same object?

<bean id="sun1" class="some.package.Sun" factory-method="getInstance" />
<bean id="sun2" class="some.package.Sun" factory-method="getInstance" />

Looking at the below

<bean id="player1" class="some.package.Player" />

<bean id="player2" ref="player1" />

I think you want to refer same bean with two or more names. If so, you can have comma separated list or ids as (alias concept)

<bean id="player1, player2" class="some.package.Player" />

Now you can refer the bean with either player1 or player2.

Similarly,

<bean id="sun1" class="some.package.Sun" factory-method="getInstance" /> <bean id="sun2" class="some.package.Sun" factory-method="getInstance" />

can be replaced with

<bean id="sun1, sun2" class="some.package.Sun" factory-method="getInstance" />

and this allows you to refer the same bean with two different ids.

And to understand when aliasing is useful, quoting from https://vladmihalcea.com/why-i-like-spring-bean-aliasing/ ,

Bean aliasing allows us to override already configured beans and to substitute them with a different object definition. This is most useful when the bean definitions are inherited from an external resource, which is out of our control.

Beans are generally singletonic, so they represent one object per context . Standard singleton design pattern in java creates one object per class loader . I think in your case you will re-create one object twice, once with Spring beans, and once with own class loader executed implementation. So both suns will be the same when you compare their hash codes via .getInstance().hashCode() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM