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

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

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

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}