[英]Spring Boot: How to inject the same instance of a prototype scoped bean into a Spring Boot Test?
[英]Prototype scope bean in controller returns the same instance - Spring Boot
我有一個控制器,其定義如下:
@RestController
public class DemoController {
@Autowired
PrototypeBean proto;
@Autowired
SingletonBean single;
@GetMapping("/test")
public String test() {
System.out.println(proto.hashCode() + " "+ single.hashCode());
System.out.println(proto.getCounter());
return "Hello World";
}
}
我已經定義了原型bean如下:
@Component
@Scope(value= ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PrototypeBean {
static int i = 0;
public int getCounter() {
return ++i;
}
}
每次我點擊http://localhost:8080/test我都會得到相同的實例並且計數器每次都會增加。 我如何確保每次都能獲得新實例? 另外我想知道為什么即使我已經將 bean 的范圍聲明為 Prototype,我也沒有得到新的實例。
您已將DemoController
聲明為@RestController
,因此它是一個具有單例范圍的 bean。 這意味着它被創建一次並且PrototypeBean
也只被注入一次。 這就是為什么每個請求都有相同的對象。
要查看原型如何工作,您必須將 bean 注入其他 bean。 這意味着,有兩個@Component
,都自動裝配PrototypeBean
, PrototypeBean
的實例在兩者中都會有所不同。
首先, static
變量與類關聯而不是與實例關聯。 刪除靜態變量。 還要添加@Lazy
注釋。 像這樣的東西
@RestController
public class DemoController {
@Autowired
@Lazy
PrototypeBean proto;
@Autowired
SingletonBean single;
@GetMapping("/test")
public String test() {
System.out.println(proto.hashCode() + " "+ single.hashCode());
System.out.println(proto.getCounter());
return "Hello World";
}
}
@Component
@Scope(value= ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PrototypeBean {
int i = 0;
public int getCounter() {
return ++i;
}
}
您要實現的目標是使用 SCOPE_REQUEST(每個 http 請求的新實例)完成的。
如果您的目標是每次調用test()
方法時都獲得PrototypeBean
新實例,請執行BeanFactory beanFactory
@Autowired
,刪除PrototypeBean
的全局類字段,並在方法test()
中檢索PrototypeBean
如下所示:
PrototypeBean proto = beanFactory.getBean(PrototypeBean.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.