Prototype Bean doesn't get autowired as expected

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

TestController.java

@RestController
public class TestController {

    @Autowired
    private TestClass testClass;

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


        
5条回答
  •  滥情空心
    2021-02-05 04:24

    As mentioned, controller is by default singleton, that's why instantiation and injection of TestClass is performed only once on its creation.

    Solution can be to inject application context and get the bean manually:

    @RestController
    public class TestController {
    
        @Autowired
        ApplicationContext ctx;
    
        @RequestMapping(value = "/test", method = RequestMethod.GET)
        public void testThread(HttpServletResponse response) throws Exception {
            ((TestClass) ctx.getBean(TestClass.class)).doSomething();
        }
    }
    

    Now, when a TestClass bean is requested, Spring knowing that it is @Prototype, will create a new instance and return it.

    Another solution is to make the controller @Scope("prototype").

提交回复
热议问题