问题
In my application (stand alone apache camel) i have to bind several beans (instances of pojos). Because those pojos could not be used directly (in java) but have to be used via bound references in urls i want to "register" all available beans in an enum. The beans are then bound like this:
public class BeanRegistry extends JndiRegistry {
public BeanRegistry() {
for (Beans bean : Beans.values()) {
try {
this.bind(bean.name(), bean.clazz().newInstance());
} catch (InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("Problem on instantiating bean " + bean.name() + " with type "
+ bean.clazz().getName() + ", cause Exception: ", e);
}
}
}
public static enum Beans {
sorter(SortingStrategy.class),
policy(PolicyForStartAndStopRoutes.class),
doneFilter(ExcludeDoneFilesFilter.class);
private final Class<?> clazz;
Beans(Class<?> clazz) {
this.clazz = clazz;
}
public Class<?> clazz() {
return clazz;
}
}
}
With this no spelling mistakes could happen as long as you use enum's name to reference a bean.
My problem is bean.clazz().newInstance()
. Is there a way to use guice to "provide" the instances? With guice i could bind the instances to arbitrary constructors or "implementations".
回答1:
I found a solution using MapBinder
. It is packed in a separate dependency:
<dependency>
<groupId>com.google.inject.extensions</groupId>
<artifactId>guice-multibindings</artifactId>
<version>3.0</version>
</dependency>
And here is my new code (it shows my guice module) it is related to my other question:
@Override
protected final void configure() {
....
// bind beans to instances
MapBinder<String, Object> boundBeans = MapBinder.newMapBinder(binder(), String.class, Object.class);
for (Beans bean : Beans.values()) {
boundBeans.addBinding(bean.name()).to(bean.clazz());
}
}
/**
*
* @param boundBeans all beans bound via a {@link MapBinder}
* @return a jndi registry with all beans (from {@link Beans}) bound
*/
@Provides
@Inject
final Registry getRegistry(final Map<String, Object> boundBeans) {
JndiRegistry registry = new JndiRegistry();
for (Entry<String, Object> boundBean : boundBeans.entrySet()) {
registry.bind(boundBean.getKey(), boundBean.getValue());
}
return registry;
}
来源:https://stackoverflow.com/questions/23225234/dynamically-bind-instances-using-guice