Prototype scope bean in controller returns the same instance - Spring Boot

陌路散爱 提交于 2020-01-25 07:56:44

问题


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";
    }
}

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;
    }
}

Everytime I hit http://localhost:8080/test I 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.


回答1:


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.

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.




回答2:


First of all, static variable is associated with class not with instance. Remove the static variable. Also add @Lazy annotation. Something like this

@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;
    }
}



回答3:


What you are trying to achieve is done by using SCOPE_REQUEST (new instance for every http request).



来源:https://stackoverflow.com/questions/55036905/prototype-scope-bean-in-controller-returns-the-same-instance-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!