Java – how to quickly create instances in CDI
•
Java
Let's suppose I have a car class In my code, I want to create 10 cars The car class has some dependencies on the @ inject annotation What is the best way to do this?
CDI has a provider interface that can be used to create cars:
@Inject Provider<Car> carProvider; public void businessMethod(){ Car car = carProvider.get(); }
Unfortunately, if I don't have carfactory, there is a method with @ produces annotation to create a car that doesn't work Although it reflects the real world that cars cannot be made without factories, I would rather not write factories for anyone I just want the CDI container to create my car like any other bean How do you recommend me to create these cars?
Solution
Just use javax enterprise. inject. Instance interface
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 ... } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码