根据这篇维基百科文章:实现依赖倒置原则 https://en.wikipedia.org/wiki/Dependency_inversion_principle#DIP_implementations可以通过两种方式完成:
- 在单独的包中对低级组件进行抽象,高级组件和低级组件都依赖于该包。
- 将低级组件的抽象驻留在高级组件的同一包中。
下图描述了使用两种方法 DIP 之前和之后的依赖关系:
Before DIP:
The repository resides in a separate maven module and has no interface, and the service has a direct dependency on the Repository implementation.
Approach 1: An interface (abstraction) of the repository is introduced. The implementation of that interface is another module, and both the service and the repository implementation have direct dependency on the interface.
Approach 2: In this approach, the interface resides in the same package of the service. The diagram http://www.martinfowler.com/eaaCatalog/separatedInterfaceSketch.gif used by Fowler to describe Separated Interface http://www.martinfowler.com/eaaCatalog/separatedInterface.html pattern seems to be also an example of this approach.
我一直在关注方法1因为我使用了 spring 的 JavaConfig,所以服务模块必须对基础设施接口和实现模块都有 ,maven 依赖关系。除了我的@Configuration
文件中,绝对没有提及任何基础设施的具体实现。
我目前正在考虑切换到方法2,但显然它不适用于 JavaConfig,因为我最终会在代码中直接引用接口实现模块,从而导致循环依赖,这是像 maven 这样的构建工具无法处理的。
问题是如何配置spring和maven来实现方法2?有什么办法可以问spring扫描组件没有添加为 Maven 依赖项?这需要改变我使用 Maven 的方式吗?