如何以静态方法以编程方式将Java CDI托管bean注入局部变量

如何以静态方法以编程方式将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(); 

@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 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 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() 
  • 您可以在静态方法中使用bean接口的类型定义参数,并传递适当的实现引用。 这将使它更适合unit testing。
  • 如果您使用的是Apache Deltaspike ,则可以使用BeanProvider#getContextualReference 。 它比获取javax.enterprise.inject.Instance更容易,但要注意依赖bean(参见javadoc)!