简体   繁体   English

Spring-Singleton工厂实例化原型范围内的bean

[英]Spring - Singleton factory instantiating prototype scoped beans

Let's say I have a factory CarFactory that returns car object 假设我有一个工厂CarFactory返回汽车对象

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 ? 有什么办法可以摆脱context.getBean吗? Somebody suggested be to inject Merc and Mclaren in the Factory and return them. 有人建议在工厂注入Merc和Mclaren并将它们退还。 But this would mean the same object is returned always. 但这意味着总是返回同一对象。 I need to create new Car objects everytime they are requested from the factory 每当工厂要求时,我都需要创建新的Car对象

Configure in your SpringApplication (or what ever your config class is named) the following bean: 在您的SpringApplication(或您的配置类的名称)中配置以下bean:

@Bean
@Scope("prototype")
public McLaren mcLarenProtyoe() {
    return new McLaren();
}

Also for Merc. 也适用于Merc。

After that you can inject via @Autowired the bean. 之后,您可以通过@Autowired注入bean。 And because of the @Scope("prototype") Spring creates every time a new bean if it gets requested. 并且由于@Scope("prototype") Spring在每次请求新bean时都会创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM