Inner beans in Spring

This artcle is taken from the book Getting started with Spring Framework

If a dependency of a bean is not shared by multiple beans, you can consider defining the dependency as an inner bean. An inner bean is defined inside a <property> or <constructor-arg> element by using the <bean> element of Spring’s beans schema. You should note that an inner bean is only accessible to the bean definition enclosing it, and not to other beans registered with the Spring container.

The following example listing shows how we generally represent bean dependencies:

<bean id="service" class="sample.spring.chapter03.springbankapp.service.FixedDepositServiceImpl">
        <property name="fixedDepositDao" ref="dao" />

<bean id="dao" class="sample.spring.chapter03.springbankapp.dao.FixedDepositDaoImpl" />

The above example listing shows that the service bean is dependent on dao bean. If service bean is the only bean that is dependent on the dao bean, then you can define the dao bean as an inner bean of service bean, as shown here:

<bean id="service" class="sample.spring.chapter02.springbankapp.service.FixedDepositServiceImpl"> 
          <property name="fixedDepositDao">
               <bean class="sample.spring.chapter02.springbankapp.dao.FixedDepositDaoImpl" /> 

In the above example listing, the bean definition for the FixedDepositDaoImpl class is inside the <property> element of service bean. If you compare the above example listing with the previous one, you’ll notice that the <property> element no longer specifies the ref attribute, and the <bean> element corresponding to FixedDepositDaoImpl class doesn’t have the id attribute anymore.


Popular posts from this blog

4th Edition of Getting started with Spring Framework now available