How to programmatically inject a Java CDI managed bean into a local variable in a (static) method
To inject an instance of class C
:
javax.enterprise.inject.spi.CDI.current().select(C.class).get()
This is available in CDI 1.1+
Use for instance this utility class. You basically have to obtain instance of BeanManager
and than grab the bean you want from it (imagine something like JNDI lookup).
Update
You could also use CDI utility class offered in CDI 1.1
SomeBean bean = CDI.current().select(SomeBean.class).get();
Update 2
In CDI 2.0 you have to use BeanManager class for obtaining bean instances programatically.
@BRS
import javax.enterprise.inject.spi.CDI;
...
IObject iObject = CDI.current().select(IObject.class, new NamedAnnotation("iObject")).get();
With:
import javax.enterprise.util.AnnotationLiteral;
public class NamedAnnotation extends AnnotationLiteral<Named> implements Named {
private final String value;
public NamedAnnotation(final String value) {
this.value = value;
}
public String value() {
return value;
}
}