簡體   English   中英

控制器中的原型作用域 bean 返回相同的實例 - Spring Boot

[英]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 ,都自動裝配PrototypeBeanPrototypeBean的實例在兩者中都會有所不同。

首先, 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM