有效管理 spring 依赖项

Manage spring dependencies efficiently

我们有一个巨大的 Java 项目,其中包含大量导致大量依赖项的模块。

假设 B 依赖于 A(一个 Spring bean)。

过去我们遇到过

如何避免或处理此类情况?我对流程、软件解决方案或指南感兴趣。

听起来您需要为项目编写更好的单元测试用例。以您的示例为例,当组件 A 更改时,B 的单元测试应该失败(A 的测试自然会失败)。我建议编写好的单元测试用例,因为确实没有其他方法可以阻止更改请求。

持续集成和测试套件应该是解决方案的一部分。当 A 更改时,依赖于 A 的所有内容都会重新测试。

下一步是确保已知 public(即在其项目之外使用)是 public,以便在进行更改时每个需要知道的人都知道。 查看您的团队和代码库的分离情况。 A 和 B 应该由同一个团队处理吗?它们应该属于同一代码库吗?

We have a huge Java project with a lot of modules leading to a lot of dependencies.

1号:

根据Spring Framework Best Practices

Do not abuse dependency injection:

As the last point, Spring ApplicationContext can create Java objects for you, but not all Java objects should be created through dependency injection. As an example, domain objects should not be created through ApplicationContext. Spring is an excellent framework, but, as far as the readability and manageability are concerned, the XML-based configuration can become an issue when many beans are defined. Overuse of dependency injection will make the XML configuration more complicated and bloated. Remember, with powerful IDEs, such as Eclipse and IntelliJ, Java code is much easier to read, maintain, and manage than XML files!

所以只在偶尔的情况下使用依赖注入,否则会让你的项目变得混乱。

I'm interested in processes, software solutions or guidelines.

如果您决定使用依赖注入,还有一些其他提示:

2号:

Prefer setter injection over constructor injection:

Spring provides three types of dependency injection: constructor injection, setter injection, and method injection. Constructor injection can ensure that a bean cannot be constructed in an invalid state, but setter injection is more flexible and manageable, especially when the class has multiple properties and some of them are optional.

3 号:

如果 B1、B2、...、Bn 依赖于 A 并且 A 经常更改,请使用工厂 class (AFactory) 并将 (Bi) 依赖于 AFactory bean 而不是 A bean。然后对于创建 A bean 的每个更改,只有 Afactory 受到影响而其他 Bi bean 不会更改。

the behaviour of A was changed so B continued working but not as expected. you could control these inconvenience by proper integration tests.

您还应该设计接口,使每个方法都有特定的明确行为。然后你假定这些方法和行为并编写 B。因此改变 A 的实现细节,不会影响 B 的行为。如果你违反 A 的行为,B 的行为就会改变,这是很自然的。实际上,仔细设计接口并防止这些问题是开发人员的责任。