[英]Spring's prototype and singleton scoped beans with regards to statefulness
[英]Spring - Singleton factory instantiating prototype scoped beans
假設我有一個工廠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);
}
}
有什么辦法可以擺脫context.getBean
嗎? 有人建議在工廠注入Merc和Mclaren並將它們退還。 但這意味着總是返回同一對象。 每當工廠要求時,我都需要創建新的Car對象
在您的SpringApplication(或您的配置類的名稱)中配置以下bean:
@Bean
@Scope("prototype")
public McLaren mcLarenProtyoe() {
return new McLaren();
}
也適用於Merc。
之后,您可以通過@Autowired
注入bean。 並且由於@Scope("prototype")
Spring在每次請求新bean時都會創建它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.