在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

实例讲解Java的Spring框架中的控制反转和依赖注入

2016-8-29 13:10| 发布者: zhangjf| 查看: 559| 评论: 0

摘要: 近来总是接触到 IoC(Inversion of Control,控制反转)、DI(Dependency Injection,依赖注入)等编程原则或者模式,而这些是著名 Java 框架 Spring、Struts 等的核心所在。针对此查了 Wikipedia 中各个条目,并从 ...

近来总是接触到 IoC(Inversion of Control,控制反转)、DI(Dependency Injection,依赖注入)等编程原则或者模式,而这些是著名 Java 框架 Spring、Struts 等的核心所在。针对此查了 Wikipedia 中各个条目,并从图书馆借来相关书籍,阅读后有些理解,现结合书中的讲解以及自己的加工整理如下:

eg1
问题描述:
开发一个能够按照不同要求生成Excel或 PDF 格式的报表的系统,例如日报表、月报表等等。

解决方案:
根据“面向接口编程”的原则,应该分离接口与实现,即将生成报表的功能提取为一个通用接口ReportGenerator,并提供生成 Excel 和 PDF格式报表的两个实现类 ExcelGenerator 和 PDFGenerator,而客户Client 再通过服务提供者 ReportService 获取相应的报表打印功能。

实现方法:
根据上面所述,得到如下类图:

201621685108610.jpg (523×261)

代码实现:

  1. interface ReportGenerator {
  2. public void generate(Table table);
  3. }
  4. class ExcelGenerator implements ReportGenerator {
  5. public void generate(Table table) {
  6. System.out.println("generate an Excel report ...");
  7. }
  8. }
  9. class PDFGenerator implements ReportGenerator {
  10. public void generate(Table table) {
  11. System.out.println("generate an PDF report ...");
  12. }
  13. }
  14. class ReportService {
  15. // 负责创建具体需要的报表生成器
  16. private ReportGenerator generator = new PDFGenerator();
  17. // private static ReportGenerator generator = new ExcelGenerator();
  18. public void getDailyReport(Date date) {
  19. table.setDate(date);
  20. // ...
  21. generator.generate(table);
  22. }
  23. public void getMonthlyReport(Month month) {
  24. table.setMonth(month);
  25. // ...
  26. generator.generate(table);
  27. }
  28. }
  29. public class Client {
  30. public static void main(String[] args) {
  31. ReportService reportService = new ReportService();
  32. reportService.getDailyReport(new Date());
  33. //reportService.getMonthlyReport(new Date());
  34. }
  35. }
复制代码


eg2
问题描述:
如上面代码中的注释所示,具体的报表生成器由 ReportService 类内部硬编码创建,由此 ReportService 已经直接依赖于 PDFGenerator 或 ExcelGenerator ,必须消除这一明显的紧耦合关系。

解决方案:引入容器
引入一个中间管理者,也就是容器(Container),由其统一管理报表系统所涉及的对象(在这里是组件,我们将其称为 Bean),包括 ReportService 和各个 XXGenerator 。在这里使用一个键-值对形式的 HashMap 实例来保存这些 Bean。

实现方法:
得到类图如下:

201621685213842.jpg (469×349)

代码实现:

  1. class Container {
  2. // 以键-值对形式保存各种所需组件 Bean
  3. private static Map<String, Object> beans;
  4. public Container() {
  5. beans = new HashMap<String, Object>();
  6. // 创建、保存具体的报表生起器
  7. ReportGenerator reportGenerator = new PDFGenerator();
  8. beans.put("reportGenerator", reportGenerator);
  9. // 获取、管理 ReportService 的引用
  10. ReportService reportService = new ReportService();
  11. beans.put("reportService", reportService);
  12. }
  13. public static Object getBean(String id) {
  14. return beans.get(id);
  15. }
  16. }
  17. class ReportService {
  18. // 消除紧耦合关系,由容器取而代之
  19. // private static ReportGenerator generator = new PDFGenerator();
  20. private ReportGenerator generator = (ReportGenerator) Container.getBean("reportGenerator");
  21. public void getDailyReport(Date date) {
  22. table.setDate(date);
  23. generator.generate(table);
  24. }
  25. public void getMonthlyReport(Month month) {
  26. table.setMonth(month);
  27. generator.generate(table);
  28. }
  29. }
  30. public class Client {
  31. public static void main(String[] args) {
  32. Container container = new Container();
  33. ReportService reportService = (ReportService)Container.getBean("reportService");
  34. reportService.getDailyReport(new Date());
  35. //reportService.getMonthlyReport(new Date());
  36. }
  37. }
复制代码


时序图大致如下:

201621685245412.jpg (594×332)

效果:
如上面所示,ReportService 不再与具体的 ReportGenerator 直接关联,已经用容器将接口和实现隔离开来了,提高了系统组件 Bean 的重用性,此时还可以使用配置文件在 Container 中实时获取具体组件的定义。

eg3
问题描述:
然而,观察上面的类图,很容易发现 ReportService 与 Container 之间存在双向关联,彼此互相有依赖关系。并且,如果想要重用 ReportService,由于它也是直接依赖于单独一个 Container 的具体查找逻辑。若其他容器具体不同的组件查找机制(如 JNDI),此时重用 ReportService 意味着需要修改 Container 的内部查找逻辑。

解决方案:引入 Service Locator
再次引入一个间接层 Service Locator,用于提供组件查找逻辑的接口,请看Wikipedia 中的描述 或者 Java EE 对其的描述1 、描述2 。这样就能够将可能变化的点隔离开来。

实现方法:
类图如下:

201621685311805.jpg (586×345)

代码实现:

  1. // 实际应用中可以是用 interface 来提供统一接口
  2. class ServiceLocator {
  3. private static Container container = new Container();
  4. public static ReportGenerator getReportGenerator() {
  5. return (ReportGenerator)container.getBean("reportGeneraator");
  6. }
  7. }
  8. class ReportService {
  9. private ReportGenerator reportGenerator = ServiceLocator.getReportGenerator();
  10. // ...
  11. }
复制代码


eg4

问题描述:
然而,不管是引入 Container 还是使用 Service Locator ,ReportService 对于具体组件的查找、创建的方式都是‘主动'的,这意味着作为客户的 ReportService 必须清楚自己需要的是什么、到哪里获取、如何获取。一下子就因为 What、Where、How 而不得不增加了具体逻辑细节。

例如,在前面‘引入Container '的实现方法中,有如下代码:

  1. class ReportService {
  2. // 消除紧耦合关系,由容器取而代之
  3. // private static ReportGenerator generator = new PDFGenerator();
  4. // 通过 Container..getBean("reportGenerator") ‘主动'查找
  5. private ReportGenerator generator = (ReportGenerator) Container
  6. .getBean("reportGenerator");
复制代码


在‘引入 Service Locator '的实现方法中,有如下代码:

  1. class ServiceLocator {
  2. privatestatic Container container = new Container();
  3. publicstatic ReportGenerator getReportGenerator() {
  4. // 还是container.getBean(), 用了委托而已
  5. return (ReportGenerator) container.getBean("reportGeneraator");
  6. }
  7. }
  8. class ReportService {
  9. // ReportService 最终还是‘主动'查找,委托给ServiceLocator 而已
  10. private ReportGenerator reportGenerator = ServiceLocator.getReportGenerator();
  11. }
复制代码


解决方案:
在这种情况下,变‘主动'为‘被动'无疑能够减少 ReportService 的内部知识(即查找组件的逻辑)。根据控制反转(IoC)原则,可江此种拉(Pull,主动的)转化成推(Push,被动的)的模式。

例如,平时使用的 RSS 订阅就是Push的应用,省去了我们一天好几次登录自己喜爱的站点主动获取文章更新的麻烦。

而依赖注入(DI)则是实现这种被动接收、减少客户(在这里即ReportService)自身包含复杂逻辑、知晓过多的弊病。

实现方法:
因为我们希望是‘被动'的接收,故还是回到 Container 的例子,而不使用 Service Locator 模式。由此得到修改后的类图如下:

201621685420071.jpg (572×349)

而原来的类图如下,可以对照着看一下,注意注释的提示:

201621685445066.jpg (578×349)

代码实现:
为了使例子能够编译、运行,并且稍微利用跟踪代码的运行结果来显式整个类图实例化、互相协作的先后顺序,在各个类的构造器中加入了不少已编号的打印语句,以及两个无关紧要的类,有点啰唆,具体如下:

  1. import java.util.Date;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. // 为了能够编译运行,多了两个无关紧要的类
  5. class Month { }
  6. class Table {
  7. publicvoid setDate(Date date) { }
  8. publicvoid setMonth(Month month) { }
  9. }
  10. // ------------ 以下均无甚重要改变 ----------------- //
  11. interface ReportGenerator {
  12. publicvoid generate(Table table);
  13. }
  14. class ExcelGenerator implements ReportGenerator {
  15. public ExcelGenerator() {
  16. System.out.println("2...开始初始化 ExcelGenerator ...");
  17. }
  18. publicvoid generate(Table table) {
  19. System.out.println("generate an Excel report ...");
  20. }
  21. }
  22. class PDFGenerator implements ReportGenerator {
  23. public PDFGenerator() {
  24. System.out.println("2...开始初始化 PDFGenerator ...");
  25. }
  26. publicvoid generate(Table table) {
  27. System.out.println("generate an PDF report ...");
  28. }
  29. }
  30. //------------ 以上均无甚重要改变 ----------------- //
  31. class Container {
  32. // 以键-值对形式保存各种所需组件 Bean
  33. privatestatic Map<String, Object> beans;
  34. public Container() {
  35. System.out.println("1...开始初始化 Container ...");
  36. beans = new HashMap<String, Object>();
  37. // 创建、保存具体的报表生起器
  38. ReportGenerator reportGenerator = new PDFGenerator();
  39. beans.put("reportGenerator", reportGenerator);
  40. // 获取、管理 ReportService 的引用
  41. ReportService reportService = new ReportService();
  42. // 注入上面已创建的具体 ReportGenerator 实例
  43. reportService.setReportGenerator(reportGenerator);
  44. beans.put("reportService", reportService);
  45. System.out.println("5...结束初始化 Container ...");
  46. }
  47. publicstatic Object getBean(String id) {
  48. System.out.println("最后获取服务组件...getBean() --> " + id + " ...");
  49. returnbeans.get(id);
  50. }
  51. }
  52. class ReportService {
  53. // private static ReportGenerator generator = new PDFGenerator();
  54. // 消除上面的紧耦合关系,由容器取而代之
  55. // private ReportGenerator generator = (ReportGenerator) Container
  56. // .getBean("reportGenerator");
  57. // 去除上面的“主动”查找,提供私有字段来保存外部注入的对象
  58. private ReportGenerator generator;
  59. // 以 setter 方式从外部注入
  60. publicvoid setReportGenerator(ReportGenerator generator) {
  61. System.out.println("4...开始注入 ReportGenerator ...");
  62. this.generator = generator;
  63. }
  64. private Table table = new Table();
  65. public ReportService() {
  66. System.out.println("3...开始初始化 ReportService ...");
  67. }
  68. publicvoid getDailyReport(Date date) {
  69. table.setDate(date);
  70. generator.generate(table);
  71. }
  72. publicvoid getMonthlyReport(Month month) {
  73. table.setMonth(month);
  74. generator.generate(table);
  75. }
  76. }
  77. publicclass Client {
  78. publicstaticvoid main(String[] args) {
  79. // 初始化容器
  80. new Container();
  81. ReportService reportService = (ReportService) Container
  82. .getBean("reportService");
  83. reportService.getDailyReport(new Date());
  84. // reportService.getMonthlyReport(new Date());
  85. }
  86. }
复制代码


运行结果:

  1. 1...开始初始化 Container ...
  2. 2...开始初始化 PDFGenerator ...
  3. 3...开始初始化 ReportService ...
  4. 4...开始注入 ReportGenerator ...
  5. 5...结束初始化 Container ...
  6. 最后获取服务组件...getBean() --> reportService ...
  7. generate an PDF report ...
复制代码


注意:
1、根据上面运行结果的打印顺序,可见代码中加入的具体编号是合理的,模拟了程序执行的流程,于是也就不再画序列图了。
2、注意该例子中对IoC、DI的使用,是以ReportService为客户端(即组件需求者)为基点的,而代码中的Client 类main()中的测试代码才是服务组件的最终用户,但它需要的不是组件,而是组件所具有的服务。
3、实际在Spring框剪中,初始化Container显然不是最终用户Client应该做的事情,它应该由服务提供方事先启动就绪。
4、在最终用户Client中,我们还是用到Container.getBean("reportService")来获取事先已在Container的构造函数中实例化好的服务组件。而在具体应用中,通常是用XML等配置文件将可用的服务组件部署到服务器中,再由Container读取该配置文件结合反射技术得以创建、注入具体的服务组件。

分析:
之前是由ReportService主动从Container中请求获取服务组件,而现在是被动地等待Container注入(Inject,也就是Push)服务组件。控制权明显地由底层模块(ReportService 是组件需求者)转移给高层模块(Container 是组件提供者),也就是控制反转了。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-7 04:29

Copyright 2015-2025 djqfx

返回顶部