實例講解Java的Spring框架中的控制反轉和依賴注入
近來總是接觸到 IoC(Inversion of Control,控制反轉)、DI(Dependency Injection,依賴注入)等編程原則或者模式,而這些是著名 Java 框架 Spring、Struts 等的核心所在。針對此查了 Wikipedia 中各個條目,并從圖書館借來相關書籍,閱讀后有些理解,現(xiàn)結合書中的講解以及自己的加工整理如下:
eg1
問題描述:
開發(fā)一個能夠按照不同要求生成Excel或 PDF 格式的報表的系統(tǒng),例如日報表、月報表等等。
解決方案:
根據(jù)“面向接口編程”的原則,應該分離接口與實現(xiàn),即將生成報表的功能提取為一個通用接口ReportGenerator,并提供生成 Excel 和 PDF格式報表的兩個實現(xiàn)類 ExcelGenerator 和 PDFGenerator,而客戶Client 再通過服務提供者 ReportService 獲取相應的報表打印功能。
實現(xiàn)方法:
根據(jù)上面所述,得到如下類圖:

代碼實現(xiàn):
interface ReportGenerator {
public void generate(Table table);
}
class ExcelGenerator implements ReportGenerator {
public void generate(Table table) {
System.out.println("generate an Excel report ...");
}
}
class PDFGenerator implements ReportGenerator {
public void generate(Table table) {
System.out.println("generate an PDF report ...");
}
}
class ReportService {
// 負責創(chuàng)建具體需要的報表生成器
private ReportGenerator generator = new PDFGenerator();
// private static ReportGenerator generator = new ExcelGenerator();
public void getDailyReport(Date date) {
table.setDate(date);
// ...
generator.generate(table);
}
public void getMonthlyReport(Month month) {
table.setMonth(month);
// ...
generator.generate(table);
}
}
public class Client {
public static void main(String[] args) {
ReportService reportService = new ReportService();
reportService.getDailyReport(new Date());
//reportService.getMonthlyReport(new Date());
}
}
eg2
問題描述:
如上面代碼中的注釋所示,具體的報表生成器由 ReportService 類內部硬編碼創(chuàng)建,由此 ReportService 已經(jīng)直接依賴于 PDFGenerator 或 ExcelGenerator ,必須消除這一明顯的緊耦合關系。
解決方案:引入容器
引入一個中間管理者,也就是容器(Container),由其統(tǒng)一管理報表系統(tǒng)所涉及的對象(在這里是組件,我們將其稱為 Bean),包括 ReportService 和各個 XXGenerator 。在這里使用一個鍵-值對形式的 HashMap 實例來保存這些 Bean。
實現(xiàn)方法:
得到類圖如下:

代碼實現(xiàn):
class Container {
// 以鍵-值對形式保存各種所需組件 Bean
private static Map<String, Object> beans;
public Container() {
beans = new HashMap<String, Object>();
// 創(chuàng)建、保存具體的報表生起器
ReportGenerator reportGenerator = new PDFGenerator();
beans.put("reportGenerator", reportGenerator);
// 獲取、管理 ReportService 的引用
ReportService reportService = new ReportService();
beans.put("reportService", reportService);
}
public static Object getBean(String id) {
return beans.get(id);
}
}
class ReportService {
// 消除緊耦合關系,由容器取而代之
// private static ReportGenerator generator = new PDFGenerator();
private ReportGenerator generator = (ReportGenerator) Container.getBean("reportGenerator");
public void getDailyReport(Date date) {
table.setDate(date);
generator.generate(table);
}
public void getMonthlyReport(Month month) {
table.setMonth(month);
generator.generate(table);
}
}
public class Client {
public static void main(String[] args) {
Container container = new Container();
ReportService reportService = (ReportService)Container.getBean("reportService");
reportService.getDailyReport(new Date());
//reportService.getMonthlyReport(new Date());
}
}
時序圖大致如下:

效果:
如上面所示,ReportService 不再與具體的 ReportGenerator 直接關聯(lián),已經(jīng)用容器將接口和實現(xiàn)隔離開來了,提高了系統(tǒng)組件 Bean 的重用性,此時還可以使用配置文件在 Container 中實時獲取具體組件的定義。
eg3
問題描述:
然而,觀察上面的類圖,很容易發(fā)現(xiàn) ReportService 與 Container 之間存在雙向關聯(lián),彼此互相有依賴關系。并且,如果想要重用 ReportService,由于它也是直接依賴于單獨一個 Container 的具體查找邏輯。若其他容器具體不同的組件查找機制(如 JNDI),此時重用 ReportService 意味著需要修改 Container 的內部查找邏輯。
解決方案:引入 Service Locator
再次引入一個間接層 Service Locator,用于提供組件查找邏輯的接口,請看Wikipedia 中的描述 或者 Java EE 對其的描述1 、描述2 。這樣就能夠將可能變化的點隔離開來。
實現(xiàn)方法:
類圖如下:

代碼實現(xiàn):
// 實際應用中可以是用 interface 來提供統(tǒng)一接口
class ServiceLocator {
private static Container container = new Container();
public static ReportGenerator getReportGenerator() {
return (ReportGenerator)container.getBean("reportGeneraator");
}
}
class ReportService {
private ReportGenerator reportGenerator = ServiceLocator.getReportGenerator();
// ...
}
eg4
問題描述:
然而,不管是引入 Container 還是使用 Service Locator ,ReportService 對于具體組件的查找、創(chuàng)建的方式都是‘主動'的,這意味著作為客戶的 ReportService 必須清楚自己需要的是什么、到哪里獲取、如何獲取。一下子就因為 What、Where、How 而不得不增加了具體邏輯細節(jié)。
例如,在前面‘引入Container '的實現(xiàn)方法中,有如下代碼:
class ReportService {
// 消除緊耦合關系,由容器取而代之
// private static ReportGenerator generator = new PDFGenerator();
// 通過 Container..getBean("reportGenerator") ‘主動'查找
private ReportGenerator generator = (ReportGenerator) Container
.getBean("reportGenerator");
在‘引入 Service Locator '的實現(xiàn)方法中,有如下代碼:
class ServiceLocator {
privatestatic Container container = new Container();
publicstatic ReportGenerator getReportGenerator() {
// 還是container.getBean(), 用了委托而已
return (ReportGenerator) container.getBean("reportGeneraator");
}
}
class ReportService {
// ReportService 最終還是‘主動'查找,委托給ServiceLocator 而已
private ReportGenerator reportGenerator = ServiceLocator.getReportGenerator();
}
解決方案:
在這種情況下,變‘主動'為‘被動'無疑能夠減少 ReportService 的內部知識(即查找組件的邏輯)。根據(jù)控制反轉(IoC)原則,可江此種拉(Pull,主動的)轉化成推(Push,被動的)的模式。
例如,平時使用的 RSS 訂閱就是Push的應用,省去了我們一天好幾次登錄自己喜愛的站點主動獲取文章更新的麻煩。
而依賴注入(DI)則是實現(xiàn)這種被動接收、減少客戶(在這里即ReportService)自身包含復雜邏輯、知曉過多的弊病。
實現(xiàn)方法:
因為我們希望是‘被動'的接收,故還是回到 Container 的例子,而不使用 Service Locator 模式。由此得到修改后的類圖如下:

而原來的類圖如下,可以對照著看一下,注意注釋的提示:

代碼實現(xiàn):
為了使例子能夠編譯、運行,并且稍微利用跟蹤代碼的運行結果來顯式整個類圖實例化、互相協(xié)作的先后順序,在各個類的構造器中加入了不少已編號的打印語句,以及兩個無關緊要的類,有點啰唆,具體如下:
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
// 為了能夠編譯運行,多了兩個無關緊要的類
class Month { }
class Table {
publicvoid setDate(Date date) { }
publicvoid setMonth(Month month) { }
}
// ------------ 以下均無甚重要改變 ----------------- //
interface ReportGenerator {
publicvoid generate(Table table);
}
class ExcelGenerator implements ReportGenerator {
public ExcelGenerator() {
System.out.println("2...開始初始化 ExcelGenerator ...");
}
publicvoid generate(Table table) {
System.out.println("generate an Excel report ...");
}
}
class PDFGenerator implements ReportGenerator {
public PDFGenerator() {
System.out.println("2...開始初始化 PDFGenerator ...");
}
publicvoid generate(Table table) {
System.out.println("generate an PDF report ...");
}
}
//------------ 以上均無甚重要改變 ----------------- //
class Container {
// 以鍵-值對形式保存各種所需組件 Bean
privatestatic Map<String, Object> beans;
public Container() {
System.out.println("1...開始初始化 Container ...");
beans = new HashMap<String, Object>();
// 創(chuàng)建、保存具體的報表生起器
ReportGenerator reportGenerator = new PDFGenerator();
beans.put("reportGenerator", reportGenerator);
// 獲取、管理 ReportService 的引用
ReportService reportService = new ReportService();
// 注入上面已創(chuàng)建的具體 ReportGenerator 實例
reportService.setReportGenerator(reportGenerator);
beans.put("reportService", reportService);
System.out.println("5...結束初始化 Container ...");
}
publicstatic Object getBean(String id) {
System.out.println("最后獲取服務組件...getBean() --> " + id + " ...");
returnbeans.get(id);
}
}
class ReportService {
// private static ReportGenerator generator = new PDFGenerator();
// 消除上面的緊耦合關系,由容器取而代之
// private ReportGenerator generator = (ReportGenerator) Container
// .getBean("reportGenerator");
// 去除上面的“主動”查找,提供私有字段來保存外部注入的對象
private ReportGenerator generator;
// 以 setter 方式從外部注入
publicvoid setReportGenerator(ReportGenerator generator) {
System.out.println("4...開始注入 ReportGenerator ...");
this.generator = generator;
}
private Table table = new Table();
public ReportService() {
System.out.println("3...開始初始化 ReportService ...");
}
publicvoid getDailyReport(Date date) {
table.setDate(date);
generator.generate(table);
}
publicvoid getMonthlyReport(Month month) {
table.setMonth(month);
generator.generate(table);
}
}
publicclass Client {
publicstaticvoid main(String[] args) {
// 初始化容器
new Container();
ReportService reportService = (ReportService) Container
.getBean("reportService");
reportService.getDailyReport(new Date());
// reportService.getMonthlyReport(new Date());
}
}
運行結果:
1...開始初始化 Container ... 2...開始初始化 PDFGenerator ... 3...開始初始化 ReportService ... 4...開始注入 ReportGenerator ... 5...結束初始化 Container ... 最后獲取服務組件...getBean() --> reportService ... generate an PDF report ...
注意:
1、根據(jù)上面運行結果的打印順序,可見代碼中加入的具體編號是合理的,模擬了程序執(zhí)行的流程,于是也就不再畫序列圖了。
2、注意該例子中對IoC、DI的使用,是以ReportService為客戶端(即組件需求者)為基點的,而代碼中的Client 類main()中的測試代碼才是服務組件的最終用戶,但它需要的不是組件,而是組件所具有的服務。
3、實際在Spring框剪中,初始化Container顯然不是最終用戶Client應該做的事情,它應該由服務提供方事先啟動就緒。
4、在最終用戶Client中,我們還是用到Container.getBean("reportService")來獲取事先已在Container的構造函數(shù)中實例化好的服務組件。而在具體應用中,通常是用XML等配置文件將可用的服務組件部署到服務器中,再由Container讀取該配置文件結合反射技術得以創(chuàng)建、注入具體的服務組件。
分析:
之前是由ReportService主動從Container中請求獲取服務組件,而現(xiàn)在是被動地等待Container注入(Inject,也就是Push)服務組件??刂茩嗝黠@地由底層模塊(ReportService 是組件需求者)轉移給高層模塊(Container 是組件提供者),也就是控制反轉了。
相關文章
SparkSQL使用IDEA快速入門DataFrame與DataSet的完美教程
本文給大家介紹使用idea開發(fā)Spark SQL 的詳細過程,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-08-08
SpringMVC使用@Valid注解進行數(shù)據(jù)驗證的方法
本篇文章主要介紹了SpringMVC使用@Valid注解進行數(shù)據(jù)驗證的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
如何使用IDEA開發(fā)Spark SQL程序(一文搞懂)
Spark SQL 是一個用來處理結構化數(shù)據(jù)的spark組件。它提供了一個叫做DataFrames的可編程抽象數(shù)據(jù)模型,并且可被視為一個分布式的SQL查詢引擎。這篇文章主要介紹了如何使用IDEA開發(fā)Spark SQL程序(一文搞懂),需要的朋友可以參考下2021-08-08
springboot整合gateway實現(xiàn)網(wǎng)關功能的示例代碼
本文主要介紹了springboot整合gateway實現(xiàn)網(wǎng)關功能的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
SpringBoot集成Quartz實現(xiàn)持久化定時接口調用任務
Quartz是功能強大的開源作業(yè)調度庫,幾乎可以集成到任何?Java?應用程序中,從最小的獨立應用程序到最大的電子商務系統(tǒng),本文將通過代碼示例給大家介紹SpringBoot集成Quartz實現(xiàn)持久化定時接口調用任務,需要的朋友可以參考下2023-07-07

