测试控制器.java
@RestController
public class TestController {
@Autowired
private TestClass testClass;
@RequestMapping(value = "/test", method = RequestMethod.GET)
public void testThread(HttpServletResponse response) throws Exception {
testClass.doSomething();
}
}
测试类.java
@Component
@Scope("prototype")
public class TestClass {
public TestClass() {
System.out.println("new test class constructed.");
}
public void doSomething() {
}
}
正如你所看到的,我正在尝试弄清楚是否有一个新的TestClass
访问“xxx/test”时已被注入。"new test class constructed."
只打印一次(我第一次触发“xxx/test”),而我期待它同样打印。是这个意思吗@Autowired
对象只能是@Singleton
?如何@Scope
然后工作吗?
EDIT:
测试控制器.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());
}
}
I tried @Valerio Vaudi
解决方案,注册为Scope(scopeName = "request")
。这是我访问“xxx/test”的三次结果
(第一次)
(second)
(third)
我不明白为什么结果为空,因为它不会在我每次使用它时重建一个新的结果。
然后我尝试了@Nikolay Rusev
解决方案@Scope("prototype")
:
(first)
(second)
(third)
这很容易理解,因为每次我使用它(TestClass)时,Spring都会自动重新生成它的新实例。但第一个场景我仍然无法理解,因为它似乎为每个请求只保留一个新实例。
真正的目的是:在每个请求生命周期中,都会有一个新的testClass
为必填项(如果需要),且只需要一项。此刻看来只有ApplicationContext
解决方案是可行的(我已经知道),但我只想知道这是否可以通过使用自动完成@Component
+ @Scope
+ @Autowired
.