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

标签 java jakarta-ee cdi

上下文:

基于我的 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/

相关文章:

java - 从 CDI 托管 bean 获取方法注释

java - 从 Firebase 实时数据库检索数据到 ListView

java - 在 ios 应用程序中收到授权码时尝试从后端服务器交换授权码时的 Redirect_uri

java - 处理请求时发生异常 : java.net.URISyntaxException:绝对 URI 中的相对路径

java - 将 HQL 转换为 SQL 查询

java - Tomcat 7/TomEE 1.6 @Webfilter 注释。没有从 Jar 中加载

java - JAX-WS 和 CDI 无法在 WAS Liberty Profile 8.5.5.6 上协同工作

java - CDI 世界中的 REST 应用程序设计选择

java - 如何使用 Java 中的函数和方法循环读取字符串

线程