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 | public class Cat { |
People.java:
1 | public class People { |
Before autowired
Beans.xml:
1 | <bean id="cat" class="com.xliu.pojo.Cat"/> |
After autowired
Beans.xml:
1 | <bean id="cat" class="com.xliu.pojo.Cat"/> |
OR
Beans.xml:
1 | <bean id="cat" class="com.xliu.pojo.Cat"/> |
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 | @Autowired |
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