测试控制器.java
@RestController
public class TestController {
@Autowired
private TestClass testClass;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void testThread(HttpServletResponse response) throws Exception {
testClass.doSomething();
}
}
TestClass.java
@Component
@Scope("prototype")
public class TestClass {
public TestClass() {
System.out.println("new test class constructed.");
}
public void doSomething() {
}
}
正如您所看到的,我正在尝试弄清楚当访问“xxx/test”时是否已注入新的TestClass
。 "new test class constructed."
仅在第一次触发“xxx/test”时打印,而我希望它被平等地打印。这是否意味着@Autowired
对象只能是@Singleton
?那么@Scope
是如何工作的呢?
编辑:
TestController.java
@RestController
public class TestController {
@Autowired
private TestClass testClass;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void testThread(HttpServletResponse response) throws Exception {
testClass.setProperty("hello");
System.out.println(testClass.getProperty());
}
}
我尝试过@Valerio Vaudi
的解决方案,注册为Scope(scopeName = "request")
。以下是当我访问“xxx/test”时的三次结果:
(第一次)
- 新测试类被构造。
- null
(第二次)
- null
(第三次)
- null
我不明白为什么结果是null,因为它每次使用时都没有重建新的实例。
然后我尝试了@Nikolay Rusev
的解决方案@Scope("prototype")
:
(第一次)
- 新实例被构造。
- 新实例被构造。
- null
(第二次)
- 新实例被构造。
- 新实例被构造。
- null
(第三次)
- 新实例被构造。
- 新实例被构造。
- null
这很容易理解,因为每次使用它(TestClass)时,Spring会自动重新生成一个新实例。但第一个场景我仍然无法理解,因为它似乎对于每个请求仅保留一个新实例。
真正的目的是:在每个请求生命周期中,需要一个新的testClass
(如果需要),并且只需要一个。此时似乎只有ApplicationContext
解决方案是可行的(我已经知道了),但我只想知道是否可以通过使用@Component
+ @Scope
+@Autowired
来自动完成这项工作。