是否总是为 RestEasy 网络服务创建新对象 class?

Is a new object created always for a RestEasy webservice class?

我们将 ReastEasy 与 JBoss EAP 6.x 一起使用。我想知道是否总是为每个 http 请求创建一个新对象。如果是,我如何停止 JBoss 为每个请求创建新对象?

我在我的 Web 服务 class 中用 javax.annotation.@PostConstruct 注释了一个 void 方法来检查是否总是在创建新对象。为了我的娱乐,方法本身没有被调用。然后我了解到 servlet 容器正在管理我的 Web 服务 classes,这就是 @PostConstruct 未被调用的原因。我说得对吗?

任何人都可以给我一些解释 web 服务生命周期的资源吗?

"I want to know if a new object is always created for every http request"

是的。请参阅 JAX-RS 规范中的 3.1.1 Lifecycle and Environment 部分:

By default a new resource class instance is created for each request to that resource.


"If yes, how can I stop jboss creating new objects for every request?"

一种方法是覆盖 Application 子类中的 getSingletons(),其中 returns 一个 Set 的资源和提供者您希望只创建一次。有关部署选项的更多信息,请参阅 Resteasy Doc。例如

@ApplicationPath("/rest")
public class RestApplication extends Application {
    private final Set<Object> singletons = new HashSet<Object>();

    public RestApplication(){
        singletons.add(new SingletnResourceClass());
    }

    @Override
    public Set<Object> getSingletons(){
        return singletons;
    }
}

"Then I understood that the servlet container is managing my web service classes and that is why the @PostConstruct is not called. Am I right?"

Java EE 中的注释由 CDI 处理,而在 JBoss 中,我们应该在 WEB-INF 中有一个 beans.xml 文件来启用 CDI 模块。


"Can anyone please point me to some resources which explains the webservice life cycle?"

上面第一个link有一些解释

有一件事我想指出:您可以将您的资源注释为 @Singleton (javax.inject.Singleton),使其只创建一次。

这个也提到了in the documentation:

@Singleton: In this scope there is only one instance per jax-rs application. Singleton resource can be either annotated with @Singleton and its class can be registered using the instance of Application. You can also create singletons by registering singleton instances into Application.