Reputation: 3070
Let's say I have a factory CarFactory
that returns car object
class CarFactory {
@Autowired
ApplicationContext context;
public Car get(String type) {
if(type.equals("Merc")
return context.getBean(Merc.class);
if(type.equals("Mclaren")
return context.getBean(Mclaren.class);
}
}
Is there any way I can get rid of that context.getBean
? Somebody suggested be to inject Merc and Mclaren in the Factory and return them. But this would mean the same object is returned always. I need to create new Car objects everytime they are requested from the factory
Upvotes: 1
Views: 122
Reputation: 1593
Configure in your SpringApplication (or what ever your config class is named) the following bean:
@Bean
@Scope("prototype")
public McLaren mcLarenProtyoe() {
return new McLaren();
}
Also for Merc.
After that you can inject via @Autowired
the bean. And because of the @Scope("prototype")
Spring creates every time a new bean if it gets requested.
Upvotes: 4