Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Injection into producer methods

DZone's Guide to

Injection into producer methods

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}