简体   繁体   English

RESTful Web服务生命周期是否始终是每个请求?

[英]RESTful web service life cycle is *always* per request?

In Beginning Java EE 7 by Antonio Goncalves it is written: Antonio Goncalves撰写的Beginning Java EE 7中写道:

In the section Writing RESTful Web Services -> Life Cycle and Callback : 在“ 编写RESTful Web服务->生命周期和回调”部分

Thus, the life cycle of a RESTful web service is per request so the service does not have to worry about concurrency and can use instance variables safely. 因此,RESTful Web服务的生命周期是针对每个请求的,因此该服务不必担心并发性,并且可以安全地使用实例变量。

Yet a couple lines later he writes: 几行之后,他写道:

Remember that a RESTful web service can also be annotated with @Stateless or @Singleton to benefit from the services of session beans. 请记住,RESTful Web服务也可以使用@Stateless或@Singleton进行注释,以受益于会话bean的服务。

So what is it? 那是什么 Lifecycle per request only or can it be session too? 每个请求的生命周期还是也可以是会话?

In addition to that, if the life cycle is session, how does it handle the @Context annotation when injecting HttpHeaders into an attribute? 除此之外,如果生命周期是会话,那么在将HttpHeaders注入属性时,它如何处理@Context注释? The headers could vary during the session, so is this attribute always updated after each request? 标头在会话期间可能会有所不同,因此此属性是否总是在每次请求后更新?

According to the JAX-RS specification, every implementation (like Jersey) must support the per-request behaviour: 根据JAX-RS规范,每个实现(例如Jersey)都必须支持每个请求的行为:

3.1.1 Lifecycle and Environment 3.1.1生命周期和环境

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. 首先调用构造函数(请参阅第3.1.2节),然后注入任何请求的依赖项(请参见第3.2节),然后调用适当的方法(请参见第3.3节),最后使该对象可用于垃圾回收。

An implementation MAY offer other resource class lifecycles, mechanisms for specifying these are outside the scope of this specification. 一个实现可以提供其他资源类生命周期,用于指定它们的机制不在本规范的范围之内。 Eg an implementation based on an inversion-of-control framework may support all of the lifecycle options provided by that framework. 例如,基于控制反转框架的实现可以支持该框架提供的所有生命周期选项。

This means if your Resource class is not additionally annotated, it is per-request. 这意味着,如果没有额外注释您的Resource类,则它是每个请求的。 One well-known exception are the Spring beans: if your Rest Resource is also a Spring Bean, then Spring specifies the lifecycle of that class. Spring Bean是一个众所周知的例外:如果您的Rest Resource也是Spring Bean,则Spring指定该类的生命周期。 The same about the EJBs (@Singleton) EJB也是如此(@Singleton)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM