我有一个java Rest api。我想知道的是:
假设一个特定客户端(例如,名为 X 的人正在使用计算机 Y)对同一 uri 进行了 3 次调用。 (例如 https://stackoverflow.com/firstname/kasav/lastname/bere )。此外,假设资源有一个非静态计数器。
class ResourceA{
int count = 0;
@Get
public Response service(){
count++;
//return count below
}
}
现在调用者是否对所有三个调用都获得相同的响应:
1
或者调用者在第一次调用时获取 1
,在第二次调用时获取 2
,然后在第三次调用时获取 3
。
对于你们中的一些人来说,这可能是显而易见的,但对我来说却不然。感谢您的帮助。
最佳答案
假设您正在使用正确遵循 JAX-RS 规范的内容。
3.1.1 Lifecycle and Environment
By default a new resource class instance is created for each request to that resource. First the constructor (see section 3.1.2) is called, then any requested dependencies are injected (see section 3.2), then the appropriate method (see section 3.3) is invoked and finally the object is made available for garbage collection. An implementation MAY offer other resource class lifecycles, mechanisms for specifying these are outside the scope of this specification. E.g. an implementation based on an inversion-of-control framework may support all of the lifecycle options provided by that framework.
因此,您的问题的答案是,当针对每个请求启动类(class)时,所有调用者都会收到 1
。
参见JSR-311对于 JAX-RS 规范。
关于java - Java Rest api 中的资源实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11998583/