I know that two requests with same content use different threads. And I thought that different threads will create different instances with @Controller annotation. But when I run the code below, I find my thought is wrong.
Test code:
@Controller
@RequestMapping("test")
public class TestADEDSAController {
private String string = "";
@RequestMapping("controllerTest")
@ResponseBody()
public String controllerTest(@RequestParam String string) {
return this.string += string;
}
}
The first time the response content is like:
test
The second time is like:
testtest
It seems that there is only one Test instance in the JVM.
I would like to know whether it is true that there is always only one @Controller instance in the JVM? Also, where can I find a detailed introduction about this process?
By default, Spring creates a single shared instance of the bean. The bean scope is singleton
by default. In case you need a new instance created on every request, you should define the bean scope as prototype
. This can either be done by annotating the class with @Scope("prototype")
or by defining the scope in the spring configuration xml as below:
<bean id="controllerId" class="com.package.name.TestADEDSAController" scope="prototype"/>
Please go through https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html to gain better understanding of bean scopes in spring.