gpt4 book ai didi

java - 使用 guice- Assistedinject 链接辅助注入(inject)参数

转载 作者:行者123 更新时间:2023-11-30 04:00:17 25 4
gpt4 key购买 nike

我正在使用 Guice Assisted Inject图书馆为我 build 一个工厂。我目前的设置如下:

class MyObject {
@Inject public MyObject(@Assisted FirstDep first, @Assisted SecondDep second, ThirdDep third) { /**/ }
}

class FirstDep { /* nothing to see here */ }
class SecondDep {
@Inject public SecondDep(@Assisted FirstDep first) { /**/ }
}
class ThirdDep { /* nothing to see here either */ }

class MyModule extends AbstractModule {
@Override public void configure() {
bind(ThirdDep.class);
install(new FactoryModuleBuilder().build(MyObjectFactory.class));
}
}

interface MyObjectFactory {
SecondDep createSecond(@Assisted FirstDep first);
MyObject createMyObject(@Assisted FirstDep first, @Assisted SecondDep second);
}

这迫使我使用factory.createController(first,factory.createSecond(first))显式创建SecondDep。是否可以更改我的绑定(bind),以便我可以简单地执行 factory.createController(first),它会自动使用 SecondDep 绑定(bind)和我传入的参数?

最佳答案

考虑您在此处创建的 API,尤其是关于 future 的扩展或实现。显然,您周围有许多有状态的 FirstDep 实例,因为 SecondDep 依赖于特定的 FirstDep,但 future 的 SecondDep 可能不依赖于同一个 FirstDep(或根本不依赖于任何 FirstDep)。事实上,createMyObject(first)可以是createMyObject(first,factory.createSecond(first))的简写,这是特定于您的业务案例的,我不认为Guice 中有一个简写可以做出这样的假设。

也就是说,您有两个选择。一,您可以创建一个非常小的助手:

// Encapsulate the createMyObject(first) shorthand.
class MyObjectHelper {
@Inject MyObjectFactory rawFactory;

MyObject createMyObject(FirstDep first) {
return rawFactory.createMyObject(first, rawFactory.createSecond(first));
}
}

或者,两个,您可以使用 @AssistedInject让 Guice 有效地重载构造函数:

class MyObject {
// Multiple @AssistedInject constructors, selected based on which parameters
// are marked with @Assisted.

@AssistedInject public MyObject(@Assisted FirstDep first,
SecondFactory secondFactory, ThirdDep third) {
this(first, secondFactory.createSecond(first), third);
}

@AssistedInject public MyObject(@Assisted FirstDep first,
@Assisted SecondDep second, ThirdDep third) { /**/ }
}

interface SecondFactory {
// Note that @Assisted annotations are not needed here. Every parameter in
// these interfaces is for assisted injection, by definition.
SecondDep createSecond(FirstDep first);
}

interface MyObjectFactory {
MyObject createMyObject(FirstDep first);
MyObject createMyObject(FirstDep first, SecondDep second);
}

虽然为每个类创建一个单独的工厂稍微冗长一些,但我认为您会发现它有助于保持类/工厂独立且易于遵循,并且它巧妙地避免了潜在的循环引用我一时记不起 Guice 是否支持。我倾向于将我的工厂公开为嵌套接口(interface):

class SecondDep {
interface Factory {
SecondDep create(FirstDep first);
}

@Inject public SecondDep(@Assisted FirstDep first) { /**/ }
}

...然后您可以找到并更新与其支持的类完全相邻的 Second.Factory

关于java - 使用 guice- Assistedinject 链接辅助注入(inject)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22146208/

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