1.用法
使用在applicationContext.xml头部,意思是说所有定义的bean中的所有属性,只要属性名称和bean的id或者name相同,那么就注入。
实际上,就相当于:定义的bean的所有属性上都加上了@Resource(通过名称注入)
2.实例
(1)applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-autowire="byName">
<bean id="person" class="com.mycompany.app.Person">
<property name="name" value="tom" />
</bean>
<bean id="testAutowire" class="com.mycompany.app.TestAutowire"></bean>
</beans>
(2)Person
public class Person
{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
(3)TestAutowire
public class TestAutowire {
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
(4)测试代码
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration ({"/applicationContext.xml"})
public class TestSpringTest {
@Autowired
private TestAutowire autowire;
@Test
public void test() {
System.out.println(autowire.getPerson().getName());
}
}
结果为:tom