版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
@Autowired 注释可用于在 setter 方法上自动装配 bean,就像 @Required 注释,构造函数、属性或具有任意名称和/或多个参数的方法一样
可以在 setter 方法上使用 @Autowired 批注来删除 XML 配置文件中的 元素。当 Spring 找到与 setter 方法一起使用的 @Autowired 注释时,它会尝试对该方法执行 byType 自动装配
不使用注释
定义一个单词:
public class Word {
private String wordName = "单词";
public String toString(){
return "WordName:" + wordName;
}
}
定义一张纸:
public class Paper {
private Word word;
public void setWord(Word word){
this.word = word;
}
public Word getWord(){
return word;
}
public String toString(){
return word;
}
}
spring的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd"
default-autowire="byType">
<bean id="paper" class="com.ste.Paper" >
<property name="word" ref="word" />
</bean>
<bean id="word" class="com.ste.Word" />
</beans>
使用注释
添加 context ,让 spring 自动扫描
配置文件可改写为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="com.ste" />
<bean id="paper" class="com.ste.Paper" />
<bean id="word" class="com.ste.Word" />
</beans>
把 getter/setter 都可以去掉,类可更改为:
public class Paper {
@Autowired
private Word word;
public String toString(){
return word;
}
}
这里 @Autowired 注解的意思就是,当 Spring 发现 @Autowired 注解时,将自动在代码上下文中找到和其匹配(默认是类型匹配)的 Bean,并自动注入到相应的地方去