Is the Class with @Controller annotation a single object?

1nfinity :

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?

Madhu Bhat :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113761&siteId=1