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".
I found a solution using
MapBinder
. It is packed in a separate dependency:And here is my new code (it shows my guice module) it is related to my other question: