Injection into producer methods
Join the DZone community and get the full member experience.
Join For FreeThe 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 CommandStrategyEven 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:
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;
}
}
@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
producer
Dependency injection
Opinions expressed by DZone contributors are their own.
Trending
-
Top 10 Pillars of Zero Trust Networks
-
Power BI Report by Pulling Data From SQL Tables
-
Leveraging FastAPI for Building Secure and High-Performance Banking APIs
-
Grow Your Skills With Low-Code Automation Tools
Comments