Example:
@Dependant
public class SomeStartingPoint {
@Inject
private SomeService someService;
public void doSomething(Long aLong, MyCustomObject myObject) {
NotABean notABean = new NotABean(aLong, myObject);
someService.doStuffWithNotABean(notABean);
}
}
public class NotABean {
@Inject
private WouldBePerfectIfThisWouldBeManagedBean somehowInjectedBean;
public NotABean(Long aLong, MyCustomObject myObject) {
//set state
}
}
所以问题是,是否有一种很好的方法可以将某些东西注入到NotABean对象中,该对象应该具有状态,因此由new()创建?
当然,在目前的情况下,我可以将WouldBePerfectIfThisWouldBeManagedBean作为参数传递给构造函数,但这与问题无关。
答案 0 :(得分:2)
有一种CDI 1.0方式和CDI 1.1方式来实现这一目标。 1.1方法比1.0容易得多,因此他们创造了它。
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);
假设您有一个具有注释@Inject
的字段或方法的对象的实例,它将满足这些依赖项。
在CDI 1.1中,你可以做相反的事情。使用类Unmanaged
,您可以实例化类的非托管实例。之后您需要调用setter来设置值。
Unmanaged<Foo> fooU = new Unmanaged(Foo.class);
Foo foo = fooU.newInstance().get();
另一种方法,不使用@Inject
就是使用CDI 1.1实用程序类来手动获取引用。因此,您可以执行以下操作,而不是注入SomeService
的引用:
SomeService someService = CDI.current().select(SomeService.class).get();