[英]How can I tell the CDI container to “activate” a bean?
Suppose I have some class with injections: 假设我有一些关于注射的课程:
class MyBean {
@Inject
Helper helper;
// all sorts of data
}
and this class was created in a way the CDI container is not aware of it like reflection, serialization or new
. 并且创建此类的方式是CDI容器不了解它,例如反射,序列化或
new
。 In this case the helper
is null
because the CDI did not initialize it for us. 在这种情况下,
helper
为null
因为CDI没有为我们初始化它。
Is there a way to tell CDI to "activate" the bean or at least its injection? 有没有办法告诉CDI“激活” bean或至少激活它的注入? eg, as if it was created with
Instance<MyBean>#get
? 例如,就好像它是使用
Instance<MyBean>#get
?
Right now I have a hack where I do the following: 现在,我有一个方法可以执行以下操作:
class SomeClass {
@Inject
Instance<MyBean> beanCreator;
void activateBean() {
MyBean mybean = ... // reflection/serialization/new
MyBean realBean = beanCreator.get();
Helper proxy = realBean.getHelper();
mybean.setHelper(proxy);
beanCreator.destroy(realBean);
}
}
This looks pretty bad but it works for everything I tested. 这看起来很糟糕,但它适用于我测试的所有内容。 It just shows what the end result is that I want.
它只是显示出我想要的最终结果。
Using Wildfly 10.1 if it matters. 如果重要,请使用Wildfly 10.1。
First of all, the way you use MyBean
is not a CDI way; 首先,您使用
MyBean
方式不是CDI方式。 in fact you operate on so called non-contextual object. 实际上,您对所谓的非上下文对象进行操作。 What you are doing is taking a non-CDI managed object and asking CDI to resolve injection points.
您正在做的是获取非CDI管理的对象,并要求CDI解决注入点。 This is quite unusual, as you handle part of the lifecycle (creation/destruction), while asking CDI to do the rest.
这是非常不寻常的,因为您处理了生命周期的一部分(创建/销毁),而要求CDI完成其余的工作。
In your case, the MyBean
class needs to become InjectionTarget
, and that is the way you should start looking. 在您的情况下,
MyBean
类需要成为InjectionTarget
,这就是您应该开始寻找的方式。 In order to trigger injection you will want to do something like this (during creation of MyBean
): 为了触发注入,您将需要执行以下操作(在创建
MyBean
期间):
// Create an injection target from your given class
InjectionTarget<MyBean> it = beanManager.getInjectionTargetFactory(beanManager.createAnnotatedType(MyBean.class))
.createInjectionTarget(null);
CreationalContext<MyBean> ctx = beanManager.createCreationalContext(null);
MyBean instance = new MyBean();
it.postConstruct(instance); // invoke @PostContruct
it.inject(instance, ctx); // trigger actual injection on the instance
Please note that this approach is usually clumsy (as in hard to make it work and maintain) and it might be better to instead turn your MyBean
into a true CDI bean and leaving whole lifecycle management to CDI. 请注意,这种方法通常很笨拙(因为很难使其工作和维护),最好将
MyBean
变成真正的CDI bean,而将整个生命周期管理交给CDI可能更好。 For that, however, your question doesn't provide enough information. 为此,您的问题没有提供足够的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.