Prototype Bean doesn't get autowired as expected

后端 未结 5 818
南旧
南旧 2021-02-05 04:14

TestController.java

@RestController
public class TestController {

    @Autowired
    private TestClass testClass;

    @RequestMapping(value = \"/test\", method         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 04:28

    all the answers above are correct. Controller by default is singleton and the injected testClass is instantiated once, because default scoped proxy mode is DEFAULT from spring doc.

    public abstract ScopedProxyMode proxyMode Specifies whether a component should be configured as a scoped proxy and if so, whether the proxy should be interface-based or subclass-based. Defaults to ScopedProxyMode.DEFAULT, which typically indicates that no scoped proxy should be created unless a different default has been configured at the component-scan instruction level.

    Analogous to support in Spring XML.

    See Also: ScopedProxyMode Default: org.springframework.context.annotation.ScopedProxyMode.DEFAULT

    if you want new instance to be injected every time you need, you should change your TestClass to :

    @Component
    @Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
    public class TestClass {
    
        public TestClass() {
            System.out.println("new test class constructed.");
        }
    
        public void doSomething() {
    
        }
    
    }
    

    with this additional configuration the injected testClass will not be really a TestClass bean but proxy to TestClass bean and this proxy will understand the prototype scope and will return new instance every time is needed.

提交回复
热议问题