Java 在GUI中使用Mapbinder在模块中使用Inject
我正在使用Guice MapBinder将接口的不同实现绑定到特定键。问题是,我需要在这些绑定中注入一些依赖项。我认为这是不可能的,因为我需要通过以下方式初始化模块:Java 在GUI中使用Mapbinder在模块中使用Inject,java,dependency-injection,guice,Java,Dependency Injection,Guice,我正在使用Guice MapBinder将接口的不同实现绑定到特定键。问题是,我需要在这些绑定中注入一些依赖项。我认为这是不可能的,因为我需要通过以下方式初始化模块: Guice.createInjector(new SomeModule()); 有可能吗 编辑:更完整的示例: 接口: public interface SomeInterface { String getName(); } 实施: public class SomeImplementation imlements Som
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
}
}
公共类SomeModule扩展了AbstractModule{
@凌驾
受保护的void configure(){
MapBinder=MapBinder.newMapBinder(binder(),String.class,SomeInterface.class);
//装订材料
}
}
编辑2:
问题是,我使用反射来获得接口的所有实现。要调用方法“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();
}
}
protectedvoid-configure(){
MapBinder=MapBinder.newMapBinder(binder(),String.class,SecureToken.class);
试一试{
设置您不再是“绑定”,您有(IMO)一个工厂。因此您应该公开它。
注意:您可以注入注入器,这(对于工厂来说)是一件非常好的事情。您可以展示一个更完整的示例,说明您正在尝试做什么吗?我仍然没有看到这个问题。binder.addBinding(“fred”).to(SomeImplementation.class)
老实说,这感觉像是一个糟糕的设计。如果必须这样的话,我想我会公开一个被Guice拿走的SomeInterface工厂,公开一个get(String)
。是的,我想设计的时间越长,我也越相信它完全是废话。我想,我会扔掉所有花哨的反射东西。。