Spring MVC RestController范围

Bab*_*mes 9 java spring spring-mvc spring-restcontroller

我有以下Spring控制器:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

每次我访问REST API时,它都会返回一个递增的值.我只是在学习Java,我想知道为什么它并不总是返回1,因为AtomicLong每次请求到来时都必须创建一个必须创建的新实例.

Tun*_*aki 12

不,这个TestController豆实际上是一个单身人士.@RestController注释声明一个Spring,@Component其范围是默认的SINGLETON.这在@Scope注释中记录:

默认为空字符串(""),表示SCOPE_SINGLETON.

这意味着TestController它将处理每个请求的相同实例.由于counter是实例变量,因此对于每个请求都是相同的.