gpt4 book ai didi

java - 在 Guice 中使用 Mapbinder 在模块中使用 Inject

转载 作者:行者123 更新时间:2023-11-30 03:09:20 26 4
gpt4 key购买 nike

我正在使用 Guice MapBinder 将接口(interface)的不同实现绑定(bind)到特定的键。问题是,我需要在这些绑定(bind)中注入(inject)一些依赖项。我认为这是不可能的,因为我需要通过这样做来初始化模块:

Guice.createInjector(new SomeModule());

有可能吗?

编辑:更完整的示例:

界面:

public interface SomeInterface {
String getName();
}

实现:

public class SomeImplementation imlements SomeInterface{
@Inject
public SomeImplementation(SomeDependency someDep){
//this needs to be injected
}

@Override
public String getName(){
//getNameFromDependency
}
}

模块:

public class SomeModule extends AbstractModule {

@Override
protected void configure() {
MapBinder<String, SecureToken> binder = MapBinder.newMapBinder(binder(), String.class, SomeInterface.class);

//bind stuff
}
}

编辑2:问题是,我使用反射来获取接口(interface)的所有实现。要调用方法“getName”,我需要调用newInstance。这似乎是问题所在...:-/

protected void configure() {
MapBinder<String, SomeInterface> binder = MapBinder.newMapBinder(binder(), String.class, SecureToken.class);
try {
Set<Class<? extends SomeInterface>> subTypes = reflections.getSubTypesOf(SecureToken.class);
for (Class<? extends SecureToken> clazz : subTypes) {
SomeInterface someInterface = clazz.newInstance();
String name = someInterface.getName();
binder.addBinding(name).toInstance(someInterface);
}
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}

最佳答案

你不再“具有约束力”,你拥有(IMO)一家工厂。所以你应该这样公开它。注意:您可以注入(inject)注入(inject)器(对于工厂来说)这是一件非常好的事情。

关于java - 在 Guice 中使用 Mapbinder 在模块中使用 Inject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954616/

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