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.
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.