TestController.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() {
}
}
As you can see, I'm trying to figure out whether a new TestClass
has been injected when visit "xxx/test". "new test class constructed."
got printed only once(first time I triggered "xxx/test") while I was expecting it printed equally. Is that mean @Autowired
object can only be @Singleton
? How does @Scope
work then?
EDIT:
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());
}
}
I tried @Valerio Vaudi
solution, registered as Scope(scopeName = "request")
. Here is the three time result when I visit "xxx/test"
(first time)
- new test class constructed.
- null
(second)
- null
(third)
- null
I don't understand why the result is null since it doens't reconstruct a new one each time I use it.
Then I tried @Nikolay Rusev
solution @Scope("prototype")
:
(first)
- new one constructed.
- new one constructed.
- null
(second)
- new one constructed.
- new one constructed.
- null
(third)
- new one constructed.
- new one constructed.
- null
This is rather easy to understand since each time I use it(TestClass), Spring auto-regenerate a new instance of it. But the first scene I still cannot understand since it seems to retain only one new instance for each request.
The real purpose is: In each request lifecycle, a new testClass
is required(if needed), and only one is required. At this moment it seems only ApplicationContext
solution is feasible(which I already knew), but I just want to know if this could be done automatically by using @Component
+ @Scope
+ @Autowired
.