[英]How to programmatically inject a Java CDI managed bean into a local variable in a (static) method
如何以靜態方法以編程方式將Java CDI 1.1+托管bean注入局部變量?
要注入類C
的實例:
javax.enterprise.inject.spi.CDI.current().select(C.class).get()
在CDI 1.1+中可用
例如使用此實用程序類 。 基本上,您必須獲取BeanManager
實例,然后從中獲取想要的bean(想象一下類似JNDI查找的東西)。
更新資料
您還可以使用CDI 1.1中提供的CDI實用程序類
SomeBean bean = CDI.current().select(SomeBean.class).get();
更新2
在CDI 2.0中,必須使用BeanManager類以編程方式獲取Bean實例。
@BRS
import javax.enterprise.inject.spi.CDI;
...
IObject iObject = CDI.current().select(IObject.class, new NamedAnnotation("iObject")).get();
帶有:
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;
}
}
@Petr Mensik建議的鏈接非常有用。 我在示例中使用了相同的代碼。
這是在實例方法/靜態方法中獲取類的實例的方法。 最好為接口編碼而不是使用方法中硬編碼的類名。
@Named(value = "iObject ")
@RequestScoped
class IObjectImpl implements IObject {.....}
//And in your method
IObject iObject = (IObject) ProgrammaticBeanLookup.lookup("iObject");
.........
//Invoke methods defined in the interface
當您的應用程序范圍內的對象的方法需要一個隨時間變化的類的實例時,這種以編程方式查找bean可能會非常有用。 因此,提取接口並使用編程bean查找總是更好的方法,以實現松散耦合。
您應該包括限定詞:
List<Annotation> qualifierList = new ArrayList();
for (Annotation annotation: C.class.getAnnotations()) {
if (annotation.annotationType().isAnnotationPresent(Qualifier.class)) {
qualifierList.add(annotation);
}
}
javax.enterprise.inject.spi.CDI.current()
.select(C.class, qualifierList.toArray(new Annotation[qualifierList.size()])
.get()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.