I am trying to have guice call my factory method to create the instance and then fill it in from inspecting it's annotations. I know I have done this before but I can't figure out how to bind the following code....
My bind code
binder.bind(ProcessorFactory.class).asEagerSingleton();
The code I am binding (and I want Guice to fill in SplineProcessor and InvertProcessor with their bindings on creation.
public class ProcessorFactory implements Provider<Processor>{
public static final ThreadLocal<String> threadLocal = new ThreadLocal<String>();
private Map<String, Class<?>> nameToClazz = new HashMap<String, Class<?>>();
public ProcessorFactory() {
nameToClazz.put("splineV1Beta", SplineProcessor.class);
nameToClazz.put("invertV1Beta", InvertProcessor.class);
}
@Override
public Processor get() {
String moduleName = threadLocal.get();
if(moduleName == null)
throw new IllegalArgumentException("Please call ProcessorFactory.threadLocal.set(moduleName)");
Class<?> clazz = nameToClazz.get(moduleName);
if(clazz == null)
return null;
try {
Object newInstance = clazz.newInstance();
return (Processor) newInstance;
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} finally {
threadLocal.set(null);
}
}
}
NOTE: I would STILL like to know how to do this though I also have this open question which is an even better way of doing the same thing guice multibinder with Providers
but unfortunately, I can't get that to work either.
NOTE: What inject code do I use as well. I am using the following code to inject(and tried ProcessorFactory as well).
@Inject
private Provider<ProcessorSetup> processors;
EDIT FOR MORE CLARIY
In a bean I have the following
@Inject
private Provider<ProcessorSetup> processors;
and when I call processors.get(), it steps into guice and then guice correctly invokes ProcessorFactory.get() and I step through that code, and my new enttiy passes through Guice to be returned to the client but is never wired up to anything. This stinks because we have @Inject in those entities we create as well. I know about 2 years ago I had this working on another project related to these posts
as I did figure out how to remove the injector at one point finally.
thanks, Dean