How to insert beans from external libraries with CDI?

How can I use JSR-299 CDI to input beans (not annotated) from external libraries?

Examples:

The X interface and its implementations come from a third-party library. How can I decide which implementation to use?

class A { @Inject private X x; } 

What if I had several classes using the X interface, but with different implementations?

 class A { @Inject private X x; // should be XDefaultImpl } class B { @Inject private X x; // should be XSpecialImpl } 
+7
java java-ee dependency-injection cdi jsr299
source share
1 answer

Use manufacturers:

 public class ClassInABeanArchive { @Produces @SpecialX public X createSpecialX() { return new XSpecialImpl(); } @Produces @DefaultX public X createDefaultX() { return new XDefaultImpl(); } } 

You will need to define the qualifiers @SpecialX and @DefaultX . and use them together with @Inject :

 @Qualifier @Retention(..) @Target(..) public @interface SpecialX {} 

If you do not need to distinguish between the two implementations, skip the part of the qualifiers.

+8
source share

All Articles