Search This Blog

Tuesday, 28 February 2012

I don't want to share my bean

In the previous example we saw how to set bean properties via the configuration. We can inject any value (or reference) into any property of the bean using the configuration files. However this leads to the side effect that the same bean reference may end up as a property among multiple beans.
For example if we have a Rockband and a Karaoke Team, both could end up having the same singer instance assigned to their singer property. While the Karaoke guys may not mind an accomplished singer, the Rock band would definitely not be happy to see their star being used by other groups. What Spring needs is some technique to ensure that a particular bean is only visible within the scope of its owning bean.
For this spring provides inner beans. Consider the below XML configuration
<bean id="rockBand" class="com.performer.Band">
    <property name="musician">
        <bean class="com.performer.Musician">
            <property name="instrument" value="Cielo"/>
        </bean>
    </property>
    <property name="singer">
        <bean class="com.performer.Singer">
            <property name="song" value="Tum Tum"/>
        </bean>
    </property>
</bean>
As can be seen above the Band object has two properties - a musician and a singer. However instead of a value or ref attribute we have instead added a bean element. Also as the bean is not referred outside the scope of the band object, there is no need to provide any identifiers to the inner beans. The below code allows us to use the rockBand object:
public class Band implements IPerformer {
    private Musician musician;
    private Singer singer;
        //setter getters

    @Override
    public void perform() {
        System.out.println("Band is performing");
        singer.perform();
        musician.perform();
        
    }

}
The code to test the same is below:
public void createComplexBeans(final BeanFactory beanFactory) {
    IPerformer rockBand = (IPerformer) beanFactory.getBean("rockBand");
    System.out.println("Bean received is " + rockBand);
    rockBand.perform();
}
The output of the below code is:
Creating new Musiscian Object com.performer.Musician@152513a
Creating a singer instance com.performer.Singer@1617189
Bean received is com.performer.Band@2bb514
Band is performing
singing Tum Tum....
Playing instrument Cielo...
As can be seen above, the Spring container instantiated the rockBand object. It came across the inner beans and instantiates each of the inner beans. The beans are then assigned to the properties of the rockBand object. These beans are also not available for any other band to use.

No comments:

Post a Comment