如何在CDI中动态创建实例

编程入门 行业动态 更新时间:2024-10-28 06:32:41
本文介绍了如何在CDI中动态创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们假设我有一个Car类。在我的代码中,我想创建10辆汽车。 Car类有一些@Inject注释依赖项。这样做的最佳方法是什么?

Let's assume I have a Car class. In my code I want to create 10 cars. Car class has some @Inject annotated dependencies. What would be the best approach to do this?

CDI有一个可以用来创建汽车的供应商界面:

CDI has a Provider interface which I can use to create the cars:

@Inject Provider<Car> carProvider; public void businessMethod(){ Car car = carProvider.get(); }

不幸的是,如果我没有CarFactory,那就行不通了一个带有@Produces注释的方法,用于创建汽车。尽管它反映了现实世界我无法在没有工厂的情况下制造汽车,但我宁愿不为所有东西编写工厂。我只是希望CDI容器像任何其他bean一样创建我的汽车。您如何推荐我创建这些汽车?

Unfortunately that doesn't work if I don't have a CarFactory that has a method with @Produces annotation which creates the car. As much as it reflects real world that I cannot create cars without a factory, I'd rather not write factories for everything. I just want the CDI container to create my car just like any other bean. How do you recommend I create those Cars?

推荐答案

只需使用javax.enterprise.inject.Instance界面。

Just use javax.enterprise.inject.Instance interface instead.

喜欢这样:

public class Bean { private Instance<Car> carInstances; @Inject Bean(@Any Instance<Car> carInstances){ this.carInstances = carInstances; } public void use(){ Car newCar = carInstances.get(); // Do stuff with car ... } }

更多推荐

如何在CDI中动态创建实例

本文发布于:2023-11-14 21:41:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588568.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   动态   如何在   CDI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!