Search code examples
javajava-ee-6cdi

How to create instances on the fly in CDI


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 has a Provider interface which I can use to create the cars:

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

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?


Solution

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

    Like this:

    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 ...
        }
    
    }