[TOC]
# 注解方式 IOC/DI
在本知識點中,講演示如何使用注解的方式完成注入對象中的效果
## 步驟 1 : 先運行,看到效果,再學習
先將完整的 spring 項目(向老師要相關資料),配置運行起來,確認可用之后,再學習做了哪些步驟以達到這樣的效果。
## 步驟 2 : 模仿和排錯
在確保可運行項目能夠正確無誤地運行之后,再嚴格照著教程的步驟,對代碼模仿一遍。
模仿過程難免代碼有出入,導致無法得到期望的運行結果,此時此刻通過比較**正確答案** ( 可運行項目 ) 和自己的代碼,來定位問題所在。
采用這種方式,**學習有效果,排錯有效率**,可以較為明顯地提升學習速度,跨過學習路上的各個檻。
## 步驟 3 : 修改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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<bean name="c" class="com.dodoke.pojo.Category">
<property name="name" value="category 1" />
</bean>
<bean name="product" class="com.dodoke.pojo.Product">
<property name="name" value="Apple Watch" />
<property name="number" value="2" />
<property name="price" value="8800" />
<!-- <property name="category" ref="c" /> -->
</bean>
</beans>
~~~
> 1. `<context:annotation-config/>`:表示告訴Spring要用注解的方式進行配置
> 2. 注入對象的語句注釋掉,這個行為在后面將使用注解來完成。
## 步驟 4 : @Autowired
在Product.java的category屬性前加上@Autowired注解
~~~
package com.dodoke.pojo;
import org.springframework.beans.factory.annotation.Autowired;
public class Product {
private int id;
private String name;
private int number;
private double price;
@Autowired
private Category category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
~~~
## 步驟 5 : 運行測試
運行 TestSpring.java,結果如下:

> 由此可見,除了使用xml配置,可以使用@Autowired注入對象。
## 步驟 6 : @Autowired的位置
除了前面的 在屬性前加上@Autowired 這種方式外,也可以在setCategory方法前加上@Autowired,這樣來達到相同的效果。
~~~
package com.dodoke.pojo;
import org.springframework.beans.factory.annotation.Autowired;
public class Product {
private int id;
private String name;
private int number;
private double price;
private Category category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Category getCategory() {
return category;
}
@Autowired
public void setCategory(Category category) {
this.category = category;
}
}
~~~
運行 TestSpring.java,結果如下:

## 步驟 7 : @Resource
除了@Autowired之外,@Resource也是常用的手段
~~~
package com.dodoke.pojo;
import javax.annotation.Resource;
public class Product {
private int id;
private String name;
private int number;
private double price;
@Resource(name="c")
private Category category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
~~~
運行 TestSpring.java,結果如下:

## 步驟 8 : 對Bean的注解
上述例子是對**注入對象行為**的注解,那么bean對象本身,比如Category,Product可不可以移出applicationContext.xml配置文件,也通過注解進行呢?
接下來就講解如何對Bean進行注解配置
## 步驟 9 : applicationContext.xml
修改applicationContext.xml,什么都去掉,只新增:`<context:component-scan base-package="com.dodoke.pojo" />`,其作用是告訴Spring,bean都放在com.dodoke.pojo這個包下。
~~~
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.dodoke.pojo" />
</beans>
~~~
## 步驟 10 : @Component
為Product類加上@Component注解,即表明此類是bean
~~~
@Component("product")
public class Product {
~~~
為Category 類加上@Component注解,即表明此類是bean
~~~
@Component("c")
public class Category {
~~~
另外,因為配置從applicationContext.xml中移出來了,所以屬性初始化放在屬性聲明上進行了。
Product
~~~
package com.dodoke.pojo;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
@Component("product")
public class Product {
private int id;
private String name = "Apple Watch";
private int number = 2;
private double price = 8800;
@Resource(name = "c")
private Category category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
~~~
Category
~~~
package com.dodoke.pojo;
import org.springframework.stereotype.Component;
@Component("c")
public class Category {
private int id;
private String name = "category 1";
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
~~~
## 步驟 11 : 運行測試
運行TestSpring,可以發現運行結果是一樣的,結果如下:

> 總結:
> 注解最大的好處就是簡化了XML配置
# 拓展資料
## 控制反轉
~~~
public class PersonServiceBean {
private PersonDao personDao = new PersonDaoBean();
public void save(Person person){
personDao.save(person);
}
}
~~~
PersonDaoBean 是在應用內部創建及維護的。所謂控制反轉就是應用本身不負責依賴對象的創建及維護,依賴對象的創建及維護是由外部容器負責的。這樣控制權就由應用轉移到了外部容器,控制權的轉移就是所謂反轉
> IOC—Inversion of Control,即“控制反轉”,不是什么技術,而是一種設計思想。在 Java 開發中,IOC 意味著將你設計好的對象交給容器控制,而不是傳統的在你的對象內部直接控制。
>
> ●誰控制誰,控制什么:傳統 Java SE 程序設計,我們直接在對象內部通過 new 進行創建對象,是程序主動去創建依賴對象;而 IOC 是有專門一個容器來創建這些對象,即由 IOC 容器來控制對象的創建;誰控制誰?當然是 IOC 容器控制了對象;控制什么?那就是主要控制了外部資源獲取(不只是對象包括比如文件等)。
> ●為何是反轉,哪些方面反轉了:有反轉就有正轉,傳統應用程序是由我們自己在對象中主動控制去直接獲取依賴對象,也就是正轉;而反轉則是由容器來幫忙創建及注入依賴對象;為何是反轉?因為由容器幫我們查找及注入依賴對象,對象只是被動的接受依賴對象,所以是反轉;哪些方面反轉了?依賴對象的獲取被反轉了。
實現 IOC 的方式:依賴注入(DI,英文quancDependency Injection)
所謂依賴注入,就是由 IOC 容器在運行期間,動態地將某種依賴關系注入到對象之中。

> IOC 對編程帶來的最大改變不是從代碼上,而是從思想上,發生了“主從換位”的變化。應用程序原本是老大,要獲取什么資源都是主動出擊,但是在 IOC/DI思想中,應用程序就變成被動的了,被動的等待IoC容器來創建并注入它所需要的資源了。
> IOC 很好的體現了面向對象設計法則之一—— 好萊塢法則:“別找我們,我們找你”;即由 IOC容器幫對象找相應的依賴對象并注入,而不是由對象主動去找。
## 依賴注入
* 使用構造器注入
* 使用屬性setter方法注入
* 使用Field注入(用于注解方式)
注入依賴對象可以采用手工裝配或自動裝配,在實際應用中建議使用手工裝配,因為自動裝配會產生未知情況,開發人員無法預見最終的裝配結果。
1. 手工裝配依賴對象
2. 自動裝配依賴對象
### 依賴注入-手工裝配
手工裝配依賴對象,在這種方式中又有兩種編程方式
1. 在xml配置文件中,通過在bean節點下配置,如
~~~
<bean id="orderService" class="cn.itcast.service.OrderServiceBean">
<constructor-arg index=“0” type=“java.lang.String” value=“xxx”/>//構造器注入
<property name=“name” value=“zhao/>//屬性setter方法注入
</bean>
~~~
2. 在java代碼中使用@Autowired或@Resource注解方式進行裝配。但我們需要在xml配置文件中配置以下信息:
~~~
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
</beans>
~~~
這個配置隱式注冊了多個對注釋進行解析處理的處理器:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor
注: @Resource注解在spring安裝目錄的lib\j2ee\common-annotations.jar
在java代碼中使用@Autowired或@Resource注解方式進行裝配,這兩個注解的區別是:@Autowired 默認按類型裝配,@Resource默認按名稱裝配,當找不到與名稱匹配的bean才會按類型裝配。
~~~
@Autowired
private PersonDao personDao;//用于字段上
@Autowired
public void setOrderDao(OrderDao orderDao) {//用于屬性的setter方法上
this.orderDao = orderDao;
}
~~~
`@Autowired` 注解是按類型裝配依賴對象,默認情況下它要求依賴對象必須存在,如果允許 null 值,可以設置它 required 屬性為 false 。如果我們想使用按名稱裝配,可以結合`@Qualifier`注解一起使用。如下:
~~~
@Autowired @Qualifier("personDaoBean")
75
private PersonDao personDao;
~~~
`@Resource` 注解和`@Autowired`一樣,也可以標注在字段或屬性的 setter 方法上,但它默認按名稱裝配。名稱可以通過`@Resource`的 name 屬性指定,如果沒有指定 name屬性,當注解標注在字段上,即默認取字段的名稱作為 bean 名稱尋找依賴對象,當注解標注在屬性的 setter 方法上,即默認取屬性名作為 bean 名稱尋找依賴對象。
~~~
@Resource(name=“personDaoBean”)
private PersonDao personDao;//用于字段上
~~~
注意:如果沒有指定 name 屬性,并且按照默認的名稱仍然找不到依賴對象時, `@Resource`注解會回退到按類型裝配。但一旦指定了 name 屬性,就只能按名稱裝配了。
### 依賴注入-自動裝配依賴對象
對于自動裝配,了解一下就可以了,不推薦使用。例子:
`<bean id="..." class="..." autowire="byType"/>`
autowire屬性取值如下:
byType:按類型裝配,可以根據屬性的類型,在容器中尋找跟該類型匹配的 bean。如果發現多個,那么將會拋出異常。如果沒有找到,即屬性值為 null。
byName:按名稱裝配,可以根據屬性的名稱,在容器中尋找跟該屬性名相同的 bean,如果沒有找到,即屬性值為 null。
### 通過在classpath自動掃描方式把組件納入spring容器中管理
在一個稍大的項目中,通常會有上百個組件,如果這些這組件采用 xml 的 bean 定義來配置,顯然會增加配置文件的體積,查找及維護起來也不太方便。spring2.5為我們引入了組件自動掃描機制,他可以在類路徑底下尋找標注了`@Component`、`@Service`、`@Controller`、`@Repository`注解的類,并把這些類納入進spring容器中管理。它的作用和在xml文件中使用 bean 節點配置組件是一樣的。要使用自動掃描機制,我們需要打開以下配置信息:
~~~
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="cn.itcast"/>
</beans>
~~~
其中`base-package`為需要掃描的包(含子包)。
`@Service`用于標注業務層組件、 `@Controller`用于標注控制層組件、`@Repository`用于標注數據訪問組件,即 DAO 組件。而`@Component`泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。
- 數據庫
- 數據庫介紹
- MySQL的安裝
- SQL
- 表基本操作
- 修改數據語句
- 數據檢索操作
- 多表數據操作
- 練習題
- JAVA
- JAVA 介紹
- JAVA 運行原理
- JDK 配置
- 類和對象
- 數據類型
- 變量
- 直接量
- 運算符
- 流程控制
- 數組結構
- 面向對象
- 隱藏和封裝
- 深入構造器
- 類的繼承
- 多態
- 包裝類
- final 修飾符
- 抽象類
- 接口
- 集合框架
- 常用類學習
- 設計模式-單例模式
- 異常處理
- JDBC
- JSP&Servlet
- Web應用
- Tomcat
- JSP
- Scriptlet
- Page 指令
- 包含指令
- 跳轉指令
- 用戶注冊實例
- JSP練習
- 內置對象
- Servlet
- 過濾器
- Web分層思想
- EL表達式
- JSTL
- 分頁實現
- AJAX&JSON
- 開發步驟
- 路徑問題
- Log4j
- Mybatis框架
- 框架介紹
- Mybatis簡單實現
- 表基本操作
- 優化配置文件
- 表字段名與實體類屬性名不同的解決方案
- 一對一關聯
- 一對多關聯
- Spring框架
- IOC/DI
- 注入對象
- 注解方式 IOC/DI
- AOP
- 注解方式AOP
- 注解方式測試
- Spring MVC框架
- Hello SpringMVC
- 視圖定位
- 注解方式
- 接受表單數據
- 客戶端跳轉
- Session
- 中文問題
- 上傳文件
- SSM整合
- 整合步驟
- 分頁
- PageHelper
- 連接池
- CRUD
- 事務管理
- JSON
- Maven
- 介紹
- 下載與配置MAVEN
- MAVEN倉庫
- ECLIPSE中的MAVEN設置
- ECLIPSE下創建MAVEN風格的JAVA項目
- 添加JAR包
- 創建MAVEN風格的JAVA WEB項目
- 創建SSM項目
- 使用ECLIPSE導入一個MAVEN風格的SSM項目
- 教學管理
- 學員名錄
- 周測統計
- 20180608
- 20180706
- 20180721
- 課堂作業
- 練習