users@jersey.java.net

Re: [Jersey] how to make resource instance to default to singleton

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Wed, 27 May 2009 06:33:35 -0700

On May 26, 2009, at 7:03 PM, Jon Pelipas wrote:

>
> Hi guys,
>
>
> I'd like to know how to configure/implement jersey to make resource
> instances to singleton by default and not to perrequest w/o putting
> annotation, i read that it was singleton before but for the latest
> version it's already perrequest?
>

The default life-cycle as always been per-request. You can annotate
your classes with @Singleton:

   https://jersey.dev.java.net/nonav/apidocs/1.1.0-ea/jersey/com/sun/jersey/spi/resource/Singleton.html

But you can override this by setting the following parameter (init-
param for Servlet):

"com
.sun
.jersey.config.property.DefaultResourceComponentProviderFactoryClass"

https://jersey.dev.java.net/nonav/apidocs/1.1.0-ea/jersey/com/sun/jersey/api/core/ResourceConfig.html
#PROPERTY_DEFAULT_RESOURCE_COMPONENT_PROVIDER_FACTORY_CLASS

For example:

         <init-param>
             <param-
name
>
com
.sun
.jersey.config.property.DefaultResourceComponentProviderFactoryClass</
param-name>
             <param-
value>com.sun.jersey.server.impl.resource.SingletonFactory</param-value>
         </init-param>



> also, with the latest release i'd like to know how to access the
> reference of the singleton resources so i can use them in my classes?
>

Yes, from an existing resource or provider you can reference a
resource using ResourceContext:

   https://jersey.dev.java.net/nonav/apidocs/1.1.0-ea/jersey/com/sun/jersey/api/core/ResourceContext.html

just inject ResourceContext into the class that requires the
reference, e.g.:

   @Context ResourceContext rc;

Paul.