问题
I have a Class with fields annotated with @Inject. I instantiate the Class using reflection, but I want the CDI to inject instances to do the Class instance fields. Is there a way of doing it?
Object myInstanceWithDependecies = Class.forName(“com.package.MyClass").newInstance();
CDI.injectAll(myInstanceWithDependecies);//This is what i want
Does someone know how to do this? I would appreciate if there was a way of doing it without scanning each field using reflection.
Thanks in advance.
回答1:
This gets the Job done
SomeBean bean = CDI.current().select(SomeBean.class).get();
回答2:
This link describes how to use OpenWebBeans in a JavaSE Application:
http://openwebbeans.apache.org/owbsetup_se.html
If you want use it for Unit Tests, i would recommend to use Arquillian:
http://arquillian.org
回答3:
In order to have CDI dependencies resolved, your instance of com.package.MyClass
has to be a managed bean (instantiated by the container), if not it is not possible to let the container resolve its dependencies.
To solve your problem you could do a programmatic lookup without creating the instance yourself:
CDI.current().select(Class.forName("com.package.MyClass")).get()
//remember to check for ambiguous or unsatisfied dependency
回答4:
If your com.package.MyClass
is not managed by CDI, it is not possible by standard CDI to inject the dependencies as pointed out by others.
However, all infrastructure is available. DeltaSpike offers the functionality you are looking for. It is also possible to use this code fragment (no dependencies on other DeltaSpike code) without including DeltaSpike.
@SuppressWarnings("unchecked")
public static <T> T injectFields(T instance) {
if (instance == null) {
return null;
}
BeanManager beanManager = CDI.current().getBeanManager();
CreationalContext<T> creationalContext = beanManager.createCreationalContext(null);
AnnotatedType<T> annotatedType =
beanManager.createAnnotatedType((Class<T>) instance.getClass());
InjectionTarget<T> injectionTarget = beanManager.createInjectionTarget(annotatedType);
injectionTarget.inject(instance, creationalContext);
return instance;
}
来源:https://stackoverflow.com/questions/36471407/java-ee-7-cdi-manual-instantiation