I want to do something like Guice's assisted injection with CDI, but
I'd prefer to not have to add CDI extensions to do it, because that
makes deployment quite messy.
I have tried a few things, but can't quite seem to find a pattern that works.
Here's a simple example. I have an object MyDaoObject that is a Data
Access Object. But, there are multiple databases, and it has to
choose the correct one. I want to construct the object via injection,
because the real version is more complicated than what you see below.
public class MyDaoObject implements MyDaoObject {
private String dbid;
@Singleton
public static class Factory {
@Inject @New
Instance<MyDaoObject> cdiFactory;
public MyDaoObject get( String dbid ) {
MyDaoObject dao = cdiFactory.get();
dao.dbid = dbid;
return dao;
}
}
}
When I try to construct one of these, the using class does something like:
@Inject MyDaoObject.Factory fact;
...
MyDaoObject = fact.get( "db12345678" );
What happens though is that two MaintDaoObjects get created. One is
prepared properly (dbid is set), the other is not.
So this apparently is not a good pattern.
Next I tried to reverse the pattern: have the Factory be the outer
class, and the MyDaoObject be a nested (non-static) class within.
This also failed, because CDI was unable to find the inner class.
I'm now not entirely sure what's the best pattern here. I'm leaning
toward having MyDaoObject have a .setDbid() method that only allows it
to be set once (yuck!) I essentially want that field to be immutable
once the object is created.
What's the best pattern to approximate assisted injection without CDI
extensions?
--Chris