Spring Setter Injection

Spring Setter Injection

Setter Injection is another method of defining bean dependencies. We can use setter based dependency injection in order to initialize the dependency. When we have fewer dependencies for a particular bean, it is better to use constructor base dependency injection.

But if we have more dependency, then it is better to use mix dependency injection that is constructor and Setter based dependency injection. Following example illustrate, how we can use setter based dependency injection:

public class ServiceBean {

 private BeanDao beanDao;
 
 public void setBeanDao(BeanDao beanDao) {
 this.beanDao = beanDao;
 }
}

Bean Definition
<beans>
 <bean id="serviceBean" class="com.package.ServiceBean">
 <property name="beanDao">
 <ref bean="beanDao"/>
 </property>
 </bean>
 <bean id="beanDao" class="com.package.BeanDao" />
</beans>


Idref element


The idref element is good to use in order to avoid error while container is validating the dependencies at the time of deployment. Container will check that bean defined actually exists or not. While ref will not perform any validation and error will occur when bean is actually requested.

For example
<beans>
 <bean id="serviceBean" class="com.package.ServiceBean">
 <property name="beanDao">
 <idref bean="beanDao"/>
 </property>
 </bean>
 <bean id="beanDao" class="com.package.BeanDao" />
</beans>

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *