为什么服务 class 变量会在每次新点击时持续存在?

Why does the service class variables persist on every new hit?

我正在处理 Spring 引导项目。我有一个使用我的服务 class 的控制器。情况是这样的,在我的服务 class 中,我有几个 class 变量用作计数器,问题是每当我到达端点时,我的计数器变量的值在每次命中时都会持续存在,这意味着如果在第一次请求时计数器值为 1,那么在第二次命中时它变为 2,依此类推。

class 变量不应该为每个新请求重置吗?我的意思是服务 class 应该是每个请求的新对象,对吗?

这基本上就是我正在做的事情。

我的控制器:

@Getmapping(path='/learningSpringBoot')
public RequestEntity<String> myMethod() {
 myServiceObject.learnSpring();
}

在我的服务中:

@Service public class Myservice {
private int counter;
 public void learnSpring() {
 System.out.println("counter : "+ counter);
 counter++;
 }
}

如果我在这里做的根本错误或完全遗漏了某些概念,请告诉我。

Shouldn't the class variables get reset for each new request? I mean the service class should be new object for each request, right?

不,@Service class 是在您启动应用程序时实例化的,因为它是 @Bean。 查看 scopes and different annotations 的工作原理。默认情况下 @Service@Scope("singleton") 所以它不会根据请求实例化,因此变量保持它们的状态。