问题描述
我试图在 Guice 的帮助下注入 String
的 ArrayList
.我想显示一个带有许多 RadioButtons 的面板(例如),用户可以在其中选择一些服务来激活.
I'm trying to inject an ArrayList
of String
s with the help of Guice. I want to show a panel with many RadioButtons (for example) where an user can select some services to activate.
一旦选定,我想获取选定服务的所有名称并将它们添加到列表中,并将此列表注入负责创建服务的经理.下面是一个例子:
Once selected, I would like to get all the names of the selected services and add them into a list, and inject this list to the manager responsible to create the services. Here is an example:
public class UIProviderModule extends ProviderServiceModule {
private ArrayList<String> requestedServices;
public UIProviderModule(ArrayList<String> requestedServices) {
this.requestedServices = requestedServices;
}
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named(Constants.REQ_SERVICES)).to(requestedServices);
bind(IParser.class).to(UIParser.class);
super.configure();
}
}
我看过很多关于 Multibindings 和提供者的帖子,但我看过不明白这对我有什么帮助.我只想检索名称,因为我不使用必须绑定到接口的类.我错过了什么吗?
I've seen many posts about Multibindings and also about Providers, but I did not understand how this could help me. I just want to retrieve names, since I'm not working with classes that have to be bound to an interface. Am I missing something?
注意:我知道这可能不是使用 Guice 的好方法,因为我提供了要绑定到 Module
的列表.
Note: I know this is maybe not the good way to use Guice because I'm giving the list to be bound to the Module
.
推荐答案
我认为您误解了模块应该如何工作.
I think you are misunderstanding how modules are supposed to work.
模块不创建对象,模块定义在需要时如何创建对象的规则.
原因MapBinder 有助于您在单选按钮列表中定义所有服务,然后使用注入的映射来激活您需要的服务.
The reason MapBinder would help is that you would define all of the services in your radio buttons list, and then use the injected map to activate the services that you need.
这里有一些代码来说明我的意思:
Here's some code to illustrate what I mean:
public class ServiceModule extends AbstractModule {
protected void configure() {
MapBinder<String, Service> mapbinder
= MapBinder.newMapBinder(binder(), String.class, Service.class);
mapbinder.addBinding("service1").to(Service1.class).in(Singleton.class);
mapbinder.addBinding("service2").to(Service2.class);
// Define ALL the services here, not just the ones being used.
// You could also look this up from a ClassLoader or read from a configuration file if you want
}
}
然后,将 MapBinder 注入您的 ServiceManager
类 - 它不是模块:
Then, inject the MapBinder to your ServiceManager
class - which is not a module:
public class ServiceManager {
private final Map<String, Service> serviceMap;
@Inject
public ServiceManager(Map<String, Service) serviceMap) {
this.serviceMap = serviceMap;
}
// This is just one way to do it. It depends on how your UI works
public void startAll(List<String> serviceList) {
for(String serviceName : serviceList) {
serviceMap.get(serviceName).start();
}
}
}
这篇关于Guice : 注入字符串的 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!