gpt4 book ai didi

java - 使用运行时数据的依赖注入(inject) : Factories and direct dependencies

转载 作者:行者123 更新时间:2023-12-01 06:22:24 25 4
gpt4 key购买 nike

我对依赖注入(inject)有一个一般性的理解问题,独立于特定的依赖注入(inject)框架。假设我有一个需要运行时参数的类:

class ClassWithRuntimeDependency {
ClassWithRuntimeDependency (String myRuntimeParameter) {
//...
}
}

现在要将此运行时参数放入我的类中,几个依赖项注入(inject)框架的文档告诉我使用工厂。该工厂采用运行时参数并创建 ClassWithRunetimeDependency 的实例用它。

但是让我们这样说ClassWithRuntimeDependency是一个非常基本的类,几乎所有其他类都需要它: Class A -> Class B -> Class C -> Factory<ClassWithRuntimeDependency> .

现在我也无法在没有这个运行时依赖的情况下创建类 C,所以我需要为它创建一个工厂。但这同样适用于 A 类和 B 类!这会导致类 A 的工厂具有运行时依赖项,仅在构造 ClassWithRuntimeDependency 时才需要该工厂。 。这意味着我不会向 A 类注入(inject)直接依赖项,这也不是最佳实践 ( github )。我知道我也可以将这种运行时依赖引入到所有需要的方法中,而不是到处使用工厂,但这只会转移问题。

我这里是否有误解或者有更好的解决方案吗?

<小时/>

为了进一步表达这个问题,如果我在任何地方都使用工厂,这可能是我的类 A-C:

// Needs a factory because of runtime parameter. 
// Imho, this is the only class which should really need a factory because
// it is the only class having the direct runtime dependency, all
// others below are indirect
class ClassWithRuntimeDependency {
ClassWithRuntimeDependency (String myRuntimeParameter) {
//...
}
}

// Needs a factory because of runtime parameter in ClassWithRuntimeDependendcy
class C {
C(String myRuntimeParameter, @inject FactoryForClassWithRuntimeDependency reallyNeededFactory) {
this.withRuntimeDependency = reallyNeededFactory(myRuntimeParameter);
}
}

// Needs a factory because of runtime parameter in C -> ClassWithRuntimeDependendcy
class B {
B(String myRuntimeParameter, @inject FactoryForC cFactory) {
this.c = cFactory(myRuntimeParameter);
}
}

// Needs a factory because of runtime parameter in B -> C -> ClassWithRuntimeDependendcy
class A {
A(String myRuntimeParameter, @inject FactoryForB bFactory) {
this.b = bFactory(myRuntimeParameter);
}
}

(我没有使用特定DI框架的语法)

所以我最终得到了 AFactory具有仅 ClassWithRuntimeDependency 需要的依赖项。当然,我也可以在构造函数中省略参数并仅使用它的方法( as suggested here ),但是如果我在这些类中的任何一个中有许多需要此参数的方法,这真的会破坏我在所有依赖类中的 API ,因此只能转移问题。

到目前为止我想到的唯一解决方案是注入(inject) context对象(或 context 对象的提供者),并用运行时数据填充此上下文对象。但这也导致temporal coupling并使其更难测试。

最佳答案

这就是为什么你应该有控制反转容器并允许他为你做肮脏的工作。就像Spring一样。您只需通过配置指出您的 bean 需要哪种依赖关系,然后 Spring 注入(inject)此依赖关系。

关于java - 使用运行时数据的依赖注入(inject) : Factories and direct dependencies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45052441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com