Spring MVC RestController scope

Babu James picture Babu James · Oct 15, 2015 · Viewed 10.4k times · Source

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.

Answer

Tunaki picture Tunaki · Oct 15, 2015

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.