Spring can wire beans automatically. To enable it, define the "autowire" attribute in <bean>.
<bean id="customer" class="com.java2s.common.Customer" autowire="byName" />
Spring has five Auto-wiring modes.
Customer Java bean.
package com.java2s.common; public class Customer { private Person person; public Customer(Person person) { this.person = person; } public void setPerson(Person person) { this.person = person; } }
Person Java bean
package com.java2s.common; public class Person { }
This is the default mode, we need to wire the Java bean via 'ref' attribute.
<bean id="customer" class="com.java2s.common.Customer"> <property name="person" ref="person" /> </bean> <bean id="person" class="com.java2s.common.Person" />
The following code add autowire byName to the bean declaration.
<bean id="customer" class="com.java2s.common.Customer" autowire="byName" />
Since the name of "person" bean is same with the name of the "customer" bean's "person" property, Spring will auto wire it via method setPerson(Person person).
<bean id="customer" class="com.java2s.common.Customer" autowire="byName" /> <bean id="person" class="com.java2s.common.Person" />
The following xml configuration declares the autowire type as byType.
<bean id="customer" class="com.java2s.common.Customer" autowire="byType" />
Since the data type of "person" bean is same as the data type of the "customer" bean's property person object, Spring will auto wire it via method setPerson(Person person).
<bean id="customer" class="com.java2s.common.Customer" autowire="byType" /> <bean id="person" class="com.java2s.common.Person" />
The following code declares a bean's autowire type as constructor
.
<bean id="customer" class="com.java2s.common.Customer" autowire="constructor" />
The data type of "person" bean is same as the constructor argument data type in "customer" bean's property (Person object), Spring will auto wire it via constructor method - "public Customer(Person person)".
<bean id="customer" class="com.java2s.common.Customer" autowire="constructor" /> <bean id="person" class="com.java2s.common.Person" />
The following code shows how to use autodetect autowire. If a constructor is found, uses "constructor"; Otherwise, uses "byType".
<bean id="customer" class="com.java2s.common.Customer" autowire="autodetect" dependency-check="objects />
Since there is a constructor in "Customer" class, Spring will auto wire it via constructor method - "public Customer(Person person)".
<bean id="customer" class="com.java2s.common.Customer" autowire="autodetect" /> <bean id="person" class="com.java2s.common.Person" />