问题描述
我是CDI的新手,曾试图找到此问题的解决方案,但没有找到任何解决方法。问题是假设我有一个正在从中注入(A)的类,其中注入了一些值(toPass),现在我想将此相同的值(toPass)传递给从A类中注入的B类。 / p>
I am new to CDI, tried to find solution for this question, but, couln't found any. Question is Suppose I have one class which is being injected(A) from, where some value(toPass) is getting injected, now I want to pass this same value(toPass) to class B, which is getting injected from class A.
public class A
{
String toPass = "abcd"; // This value is not hardcoded
@Inject
private B b;
}
public class B
{
private String toPass;
public B(String toPass)
{
toPass = toPass;
}
}
有人可以帮我吗?
注意:我们不能以与在A中初始化相同的方式来初始化B的toPass变量,对此有一些限制。基本上在春季,我们可以轻松完成此操作,但是,我想在CDI中完成它。
Can anybody please help me in this? Note: we cannot initialize the toPass variable of B in the same way as we have initialized in A, there is some restriction to it. Basically in Spring we could have done it easily, but, I wanted to do it in CDI.
推荐答案
您可以选择:
1。
将 toPass
变量从 @PostConstruct
b > Bean A
的方法:
1.Set toPass
variable to b
from @PostConstruct
method of bean A
:
@PostConstruct
public void init() {
b.setToPass(toPass);
}
或
2。
为 toPass
变量创建生产者,并将其注入到bean A
和 B
。
2.Create producer for toPass
variable and inject it into bean A
and B
.
制作人:
@Produces
@ToPass
public String produceToPass() {
...
return toPass;
}
注入:
@Inject
@ToPass
String toPass;
或
3。
如果bean A
不是依赖范围的bean,则可以使用 Provider
接口获取bean的实例 A
:
3.If bean A
is not a dependent scoped bean you can use Provider
interface to obtain an instance of bean A
:
public class B
{
@Inject
Provider<A> a;
public void doSomeActionWithToPass() {
String toPass = a.get().getToPass());
...
}
但您不应使用构造函数中的toPass或来自 @PostConstruct
方法。
But you should not use toPass from constructor or from @PostConstruct
method.
这篇关于如何将参数传递给CDI中另一个类的注入类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!