How to inject beans from external libs with CDI?
Asked Answered
A

1

7

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

}
Arcane answered 3/6, 2010 at 14:33 Comment(0)
M
8

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.

Mickeymicki answered 3/6, 2010 at 14:44 Comment(5)
I submitted it. It wasn't of quite a good quality, but the major features worked fine :) I made a sample jsf2 app to demonstrate some of the features. All others were unit-tested. Now I plan to make a presentation on CDI in front of BG JUG. We'll see :)Mickeymicki
(code.google.com/p/blinkframework it's here, but it isn't of "production interest" :) )Mickeymicki
Using an annotation with a string parameter (httpParm("foo")) is described in the Weld Documentation (but does not map directly to JSR-330): docs.jboss.org/weld/reference/1.0.0/en-US/html_single/#d0e1540Fernandes
yes, there was some strange things with the usecase. But how does it relate to this answer/question?Mickeymicki
Depends on whether the OP wants to decide on which implementation to use based on a customer qualifier or not.Fernandes

© 2022 - 2024 — McMap. All rights reserved.