欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring学习指南-第二章-Spring框架基础

程序员文章站 2023-10-16 12:35:14
第二章 Spring框架基础 面向接口编程的设计方法 ​ 在上一章中,我们看到了一个依赖于其他类的POJO类包含了对其依赖项的具体类的引用。例如,FixedDepositController 类包含 对 FixedDepositService 类的引用,FixedDepositService 类包含 ......

第二章 spring框架基础

面向接口编程的设计方法

​ 在上一章中,我们看到了一个依赖于其他类的pojo类包含了对其依赖项的具体类的引用。例如,fixeddepositcontroller 类包含 对 fixeddepositservice 类的引用,fixeddepositservice 类包含对 fixeddepositdao 类的引用。如果这个依赖于其他类的类直接引用其依赖项的类,则会导致类之间的紧密耦合。这意味着如果要替换其依赖项的其他实现,则需要更改这个依赖于其他类的类本身。

​ 我们知道 java 接口定义了其实现类应遵循的契约。因此,如果一个类依赖于其依赖项实现的接口,那么当替换不同的依赖项实现时,类不需要改变。一个类依赖于由其依赖项所实现的接口的应用程序设计方法称为 "面向接口编程"。这种设计方法使得依赖类和依赖项之间松耦合。由依赖项类实现的接口称为依赖接口。

​ 和 ”面向类编程“ 相比,”面向接口编程“ 是更加良好设计实践,下图表明 abean 类依赖于 bbean 接口而不是 bbeanimpl 类(bbean接口的实现)。

Spring学习指南-第二章-Spring框架基础

下图中,fixeddepositjdbcdao 单纯的使用 jdbc, 而 fixeddeposithibernatedao 使用 hibernate orm 进行数据库交互。如果 fixeddepositservice 直接依赖于 fixeddepositjdbcdao 或 fixeddeposithibernatedao,当需要切换与数据库交互的策略时,则需要在 fixeddepositservice 类中进行必要的更改。fixeddepositservice 依赖于 fixeddepositjdbcdao 和 fixeddeposithibernatedao 类实现 fixeddepositdao 接口(依赖接口)。现在,通过使用单纯的 jdbc 或 hibernate orm 框架,你可以向 fixeddepositservice 实例提供 fixeddepositjdbcdao 或 fixeddeposithibernatedao实例。

Spring学习指南-第二章-Spring框架基础

​ 由于 fixeddepositservice 依赖于 fixeddepositdao 接口,因此将来可以支持其他数据库交互策略。如果决定使用ibatis(mybaits)持久性框架进行数据库交互,那么可以使用ibatis,而不需要对fixeddepositservice 类进行任何更改,只需要创建一个 fixeddepositdao 接口的 fixeddepositibatisdao 类,并将 fixeddepositibatisdao 的实例提供给 fixeddepositservice 实例。

​ 现在来看看 ”面向接口编程“ 是如何提高依赖类的可测试性的。

提高依赖类的可测试性

​ 在上图中,fixeddepositserivce 类保留了对 fixeddepositdao 接口的引用。fixeddepositjdbcdao 和 fixeddeposithibernatedao 是 fixeddepositdao 接口的具体实现类。现在,为了简化 fixeddepositservice 类的单元测试,我们可以把原来对具体数据库操作的实现去掉,用一个实现了 fixeddepositdao 接口但是不需要数据库的代码来代替。

​ 如果 fixeddepositservice 类直接引用 fixeddepositjdbcdao 或 fixedeposithibernatedao 类,那么测试 fixeddepositservice 类则需要设置数据库以进行测试。这表明通过对依赖接口的模拟依赖类实现,你可以减少针对单元测试的基础设施设置的工作量。

​ 现在来看看 spring 如何在应用程序中使用 “面向接口编程” 的设计方法,你需要执行以下操作:

​ 1.创建引用依赖接口,而不是依赖项的具体实现的 bean 类;

​ 2.定义 元素,并在元素中指定所要注入依赖bean的依赖项的具体实现类。

使用 “面向接口编程” 设计方法的mybank应用程序

未完,待续......