I have the following Spring
controller:
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/test")
public String test() {
long val = counter.incrementAndGet();
return String.valueOf(val);
}
}
Each time I access the REST API, it returns an incremented value.
I am just learning Java and I am wondering why it does not always return 1 as a new instance of AtomicLong
must have been created each time the request comes.
@RestController annotation declares a Spring @Component whose scope is by default SINGLETON . This is documented in the @Scope annotation: Defaults to an empty string ("") which implies SCOPE_SINGLETON. This means that it will be the same instance of TestController that will handle every requests.
Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.
Spring MVC controllers are singleton by default and any controller object variable/field will be shared across all the requests and sessions. If the object variable should not be shared across requests, one can use @Scope("request") annotation above your controller class definition to create instance per request.
@Controller is used to mark classes as Spring MVC Controller. @RestController annotation is a special controller used in RESTful Web services, and it's the combination of @Controller and @ResponseBody annotation. It is a specialized version of @Component annotation.
No, the TestController
bean is actually a singleton. @RestController
annotation declares a Spring @Component
whose scope is by default SINGLETON
. This is documented in the @Scope
annotation:
Defaults to an empty string ("") which implies SCOPE_SINGLETON.
This means that it will be the same instance of TestController
that will handle every requests. Since counter
is an instance variable, it will be same for every request.
A @RestController
is not created for each request, it remains the same for every request. So your counter
keeps its value and is incremented each time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With