Spring Autowiring

Spring has an advanced concept of autowiring the relationships and dependencies. You don’t have to explicitly mention the properties and their values, but setting autowire property to a value allows the framework to wire them with appropriate properties.

Table 1.1 Autowiring modes
Mode Description
no No autowiring at all. Bean references must be defined via a ref element.
byName Attempts to match all properties of the autowired bean with beans that have the same name (or ID) as the properties. Properties for which there’s no matching bean will remain unwired.
byType Attempts to match all properties of the autowired bean with beans whose types are assignable to the properties. Properties for which there’s no matching bean will remain unwired.
constructor Tries to match up a constructor of the autowired bean with beans whose types are assignable to the constructor arguments.
autodetect Attempts to apply constructor autowiring first. If that fails, byType will be tried.

You can configure autowiring as following :

Autowiring “No”

This is default autowire mode. Spring will not autowire the address property of ‘employee’ bean, instead we need to specify (inject) it explicitly.

 
<bean id="employee" class="com.kruders.bean.Employee">
    <property name="name" value="Puneet" />
    <property name="address" ref="address" />
</bean>


Autowiring By “Name”

In Spring, everything is given a name. Thus bean properties are given names. This option will inspect the container and look for a bean named exactly the same as the property which needs to be autowired.

<bean id="employee" class="com.kruders.bean.Employee" autowire="byName">
	<property name="name" value="Puneet" />
</bean>


Autowiring By “Type”

Autowiring using byType works in a similar way to byName, except that instead of con-sidering a property’s name, the property’s type is examined. When attempting to autowire a property by type, Spring will look for beans whose type is assignable to the property’s type.

<bean id="employee" class="com.kruders.bean.Employee" autowire="byType">
    <property name="name" value="Puneet" />
</bean>


Autowiring By “Constructor”

If your bean is configured using constructor injection, you may choose to put away the <constructor-arg> elements and let Spring automatically choose constructor arguments from beans in the Spring context.

<bean id="employee" class="com.kruders.bean.Employee" autowire="constructor">
    <property name="name" value="Puneet" />
</bean>


Autowiring “Autodetect”

If you want to autowire your beans, but you can’t decide which type of autowiring to use, have no fear. You can set the autowire attribute to autodetect to let Spring make the decision for you. For example:

<bean id="employee" class="com.kruders.bean.Employee" autowire="autodetect">
    <property name="name" value="Puneet" />
</bean>


No comments yet.

Leave a Reply