如何在CDI中动态创建实例 [英] How to create instances on the fly in CDI

查看:223
本文介绍了如何在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中动态创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆