gpt4 book ai didi

java - 将运行时参数传递给包含注入(inject)的对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:29:37 24 4
gpt4 key购买 nike

上下文:

基于我的 Java EE 应用程序收到的 XML,我想创建一个新的 AreeConfiguration 对象,其中发生了 3 个对象的注入(inject)。根据此 XML 中的信息选择正确的 Instance<>。因此,我传递来自此 XML 的信息。

我有一个数据结构,应该在运行时用这些 AreeConfiguration 对象填充:

private HashMap<Integer, AreeConfiguration> configurations = new HashMap<Integer, AreeConfiguration>();

public void parseNewConfiguration(Element el) throws InvalidDescriptorException {
if(!isValidConfiguration(el)) throw new InvalidDescriptorException();

int key = getUniqueKey();

AreeConfiguration cfg = new AreeConfiguration(key, el);
configurations.put(key, cfg);
}

我的 AreeConfiguration 对象应该(理想情况下)用基本的 XML 信息构造并注入(inject)一些对象。稍后,我想使用 XML 中的信息来选择正确的 Instance<>。

public class AreeConfiguration {

@Inject
private Instance<AreeInput> ais;
private AreeInput ai;

@Inject
private Instance<AreeReasoner> ars;
private AreeReasoner ar;

@Inject
private Instance<AreeOutput> aos;
private AreeOutput ao;

AreeConfiguration(int key, Element el) throws InvalidDescriptorException {
...
}

@PostConstruct
public void chooseComponents(){
ai = chooseInput();
ar = chooseReasoner();
ao = chooseOutput();
}

我的发现和尝试:

通过研究(在 Stack Overflow 上),我现在了解到 CDI 不会注入(inject)使用 new Object() 创建的对象。上面显示的代码永远不会进入 chooseComponents()

当我想尝试使用@Producer 时,我用@Producer 注释parseNewConfiguration(Element el) 并添加一个@New AreeConfiguration cfg 争论。但是,我也无法传递 Element el,这很不幸,因为它包含基本的 XML 信息。

如果我没有彻底解释自己,请提出其他问题。我正在寻找一种使用 CDI 来完成上述任务的方法。

此外,这个问题的答案中提出的解决方案有多“干净”:@Inject only working for POJOs created by CDI container?

最佳答案

要对不是由 CDI 容器创建的实例执行注入(inject),并且您有权访问 BeanManager,那么您可以执行以下操作:

// Create a creational context from the BeanManager
CreationalContext creationalContext = beanManager.createCreationalContext(null);

// Create an injection target with the Type of the instance we need to inject into
InjectionTarget injectionTarget = beanManager.createInjectionTarget(beanManager.createAnnotatedType(instance.getClass()));

// Perform injection into the instance
injectionTarget.inject(instance, creationalContext);

// Call PostConstruct on instance
injectionTarget.postConstruct(instance);

可用于完成所有工作的类示例位于:http://seamframework.org/Documentation/HowDoIDoNoncontextualInjectionForAThirdpartyFramework .

关于java - 将运行时参数传递给包含注入(inject)的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16114343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com