Over a million developers have joined DZone.

Injection into producer methods

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

The implementations of strategies are instantiated using the Java new operator – this means that they will not support dependency injection and interceptors. If you want to avoid these limitations, then you can use dependency injection into the producer method to obtain bean instances:

@Produces @CommandQualifier @SessionScoped public CommandStrategy
generateCommandStrategy(SingleCommandStrategy scs, MultipleCommandStrategy mcs,
CustomCommandStrategy ccs, BasicCommandStrategy bcs) {
switch (nr) {
case 1:
return scs;
case 2:
return mcs;
case 3:
return ccs;
default:
return bcs;
}
}

Even so, this is still not a very pleasant solution - in this case, you must by extra careful with the producer method scope and the injected bean scope. Per example, if SingleCommandStrategy is in @RequestScoped, that will interfere with the producer method scope, which is @SessionScoped and will result into a scopes issue. You can fix this by changing the scope of the producer method to @Dependent or @RequestScoped or even better, use the @New qualifier annotation:
@Produces @CommandQualifier @SessionScoped public CommandStrategy
generateCommandStrategy(@New SingleCommandStrategy scs, @New
MultipleCommandStrategy mcs, @New CustomCommandStrategy ccs, @New
BasicCommandStrategy bcs) {
switch (nr) {
case 1:
return scs;
case 2:
return mcs;
case 3:
return ccs;
default:
return bcs;
}
}


Well, that is much better! Now, a new dependent instance of each implementation will be created, passed and returned by the producer method. At the end, the instance will be associated with the session context and will “survive” until the session is destroyed.

From http://e-blog-java.blogspot.com/2011/05/injection-into-producer-methods.html

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}