这篇博客主要介绍通过@autowired 注解来装配bean,包括以下内容:
1. 通过属性域注入
2. 通过set方法或则其他方法注入
3. 通过构造器方法注入
4. @autowired 的required属性
5. @autowired 的限定器@Qualifier
1. 通过属性域注入
下面通过一个实例来说明@autowired 注解实现属性域注入:
(1)entity
蛋糕类
package spring.ch2.topic2;
/**
* Created by louyuting on 17/1/20.
* 注入属性,记得属性必须要写setter方法 不然就会抛出异常,注入失败.
* 蛋糕类
*/
public class Cake {
private String name = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
厨师类
package spring.ch2.topic2;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by louyuting on 17/1/22.
*/
public class Chief {
@Autowired
private Cake cake = null;//自动注入的就不需要setter方法了
private String name = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Cake makeOneCake() {
System.out.println(getName() + " make " + cake.getName());
return cake;
}
}
这里需要注意的是,虽然我们的cake属性域是赋值为null,但是当spring容器启动时,j就会通过@Autowired标签注入cake对象。
(2)配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="blueberryCheese"
class="spring.ch2.topic2.Cake"
p:name="blueberryCheese---Cake" scope="prototype">
</bean>
<bean id="jack"
class="spring.ch2.t