简体   繁体   中英

How to inject beans from external libs with CDI?

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

Examples:

Interface X and its implementations come from a third party lib. 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 different implementations?

class A {

    @Inject 
    private X x; // should be XDefaultImpl

}

class B {

    @Inject 
    private X x; // should be XSpecialImpl

}

Use producers:

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

    @Produces @DefaultX public X createDefaultX() {
        return new XDefaultImpl();
    }
}

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

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

If you don't need to differentiate two implementations, skip the qualifiers part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM