-
1. Re: Simulating guice's Assisted Injection
atomicknight Jul 30, 2012 10:51 PM (in response to wz2b)Well, your example doesn't seem to really merit assisted injection (since it doesn't have any dependencies), but the basic template used by Guice is the following (Guice annotations noted in comments):
{code}public class Foo {
private final BarService barService;
private final Baz baz;
/*@Inject*/
private Foo( BarService barService, /*@Assisted*/ Baz baz ) {
this.barService = barService;
this.baz = baz;
}
// Foo methods
@Singleton
public static class Factory {
@Inject private BarService barService; // Or use constructor injection
public Foo create( Baz baz ) {
return new Foo( barService, baz );
}
}
}{code}
And then you use it like this:
{code}public class Qux {
@Inject private Foo.Factory fooFactory;
public void doit( Baz baz ) {
Foo foo = fooFactory.create( baz );
}
}{code}
-
2. Re: Simulating guice's Assisted Injection
wz2b Jul 30, 2012 11:07 PM (in response to atomicknight)Yeah, it was just an example .. the real class being created (in place of your example "Foo") has other stuff injected into it - a logger, a few database handlers, and so forth. It's more than I really want to pass on the constructor, though if that's the only way maybe I have to.
If I create an object with new, is there some way I can, after the fact, tell CDI to inject members?
-
3. Re: Simulating guice's Assisted Injection
atomicknight Jul 31, 2012 6:48 PM (in response to wz2b)Christopher Piggott wrote:
Yeah, it was just an example .. the real class being created (in place of your example "Foo") has other stuff injected into it - a logger, a few database handlers, and so forth. It's more than I really want to pass on the constructor, though if that's the only way maybe I have to.
If you're shooting for complete immutability, the constructor route is really the only way to go. Given that the constructor is encapsulated within the class, I don't see anything particularly distasteful about having lots of parameters.
Christopher Piggott wrote:
If I create an object with new, is there some way I can, after the fact, tell CDI to inject members?
Not really - the CDI model is based on the idea of resolving dependencies just once at startup. Though depending on your particular use case, you could potentially chain/compose a number of these factories to achieve something similar (e.g. with [non-CDI] decorators).