本文介绍了控制器中的原型作用域 bean 返回相同的实例 - Spring Boot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,定义如下:

I have a contoller which is defined as below:

@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如下:

And i have defined prototype bean as below:

@Component
@Scope(value= ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PrototypeBean {
    static int i = 0;

    public int getCounter() {
        return ++i;
    }
}

每次我点击 http://localhost:8080/test我得到相同的实例,计数器每次都会增加.我如何确保每次都能获得新实例?另外我想知道为什么即使我已经将 bean 的范围声明为 Prototype,我也没有得到新的实例.

Everytime I hit http://localhost:8080/testI get the same instance and the counter gets incremented everytime.How do I make sure that I get new instance everytime ?Also I want to know why I am not getting new instance even though I have declared the scope of the bean as Prototype.

推荐答案

您已将 DemoController 声明为 @RestController,因此它是一个具有单例作用域的 bean.这意味着它被创建一次并且 PrototypeBean 也只被注入一次.这就是为什么每个请求都有相同的对象.

You have declared DemoController as @RestController, so it's a bean with singleton scope. It means it's created once and PrototypeBean is also injected only once. That's why every request you have the same object.

要查看原型如何工作,您必须将 bean 注入其他 bean.这意味着,如果有两个 @Component,都自动装配 PrototypeBeanPrototypeBean 的实例在两者中都会有所不同.

To see how prototype works, you would have to inject the bean into other bean. This means, that having two @Components, both autowiring PrototypeBean, PrototypeBeans instance would differ in both of them.

这篇关于控制器中的原型作用域 bean 返回相同的实例 - Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:37