ffff
ffff

Reputation: 3070

Spring - Singleton factory instantiating prototype scoped beans

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

Answers (1)

smsnheck
smsnheck

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

Related Questions