The Spring container can autowire relationships between collaborating beans.
Example
Dog.java:
1
2
3
4
5 public class Dog {
public void shout() {
System.out.println("wang");
}
}
Cat.java:1
2
3
4
5public class Cat {
public void shout() {
System.out.println("miao");
}
}
People.java:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25public class People {
private Cat cat;
private Dog dog;
private String name;
@Override
public String toString() {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}';
}
public Cat getCat() {return cat;}
public void setCat(Cat cat) {this.cat = cat;}
public Dog getDog() {return dog;}
public void setDog(Dog dog) {this.dog = dog;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
Before autowired
Beans.xml:1
2
3
4
5
6
7
8<bean id="cat" class="com.xliu.pojo.Cat"/>
<bean id="dog" class="com.xliu.pojo.Dog"/>
<bean id="people" class="com.xliu.pojo.People">
<property name="name" value="xliu"/>
<property name="dog" ref="dog"/>
<property name="cat" ref="cat"/>
</bean>
After autowired
Beans.xml:1
2
3
4
5
6<bean id="cat" class="com.xliu.pojo.Cat"/>
<bean id="dog" class="com.xliu.pojo.Dog"/>
<bean id="people" class="com.xliu.pojo.People" autowire="byName">
<property name="name" value="xliu"/>
</bean>
OR
Beans.xml:1
2
3
4
5
6<bean id="cat" class="com.xliu.pojo.Cat"/>
<bean id="dog" class="com.xliu.pojo.Dog"/>
<bean id="people" class="com.xliu.pojo.People" autowire="byType">
<property name="name" value="xliu"/>
</bean>
Noticed that both codes omit the ref=""
, because using autowire enable spring to automatically search in the context and match the property.
byName & byType
autowire has two value: byName, byType.
byName: automatically search in context and match the suffix of
setXXX
of object with corresponding beanid.For example, class people has method
setDog()
and there is abean id ="dog"
, they will match. If we change the id to dog222, then they won’t match and error occurs.byType: automatically search in context and match the class of object with corresponding beanclass. If using byType, we can even skip define bean id because only class is used to match.
The disadvantage of byType is we can’t register two beans refer to the same class.
Using annotaion
Place @Autowired
before the attribute in pojo, for example:1
2
3
4@Autowired
private Cat cat;
@Autowired
private Dog dog;
Turn on the support for annotaion in xml:1
<context:annotation-config/>
With such configuration, many lines can be omitted, we only need:1
<bean id="people" class="com.xliu.pojo.People"/>
So, this method is based on byType