Hi Jack,
You can simply attach @Singleton annotation to your resource to avoid
new instances per request
(
http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/resource/Singleton.html)
Other solution is to make your datasource connection available as a
singleton through injection to all the resources - e.g. you can inject
it by using @Context annotation, or even come up with your own
annotation you would use for injecting it.
To enable that, you can implement SingletonTypeInjectableProvider
(
http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/inject/SingletonTypeInjectableProvider.html).
E.g. like this:
@Provider
public class DSConnectionProvider extends
SingletonTypeInjectableProvider<Context, Connection> {
public DSConnectionProvider() {
super(Connection.class, <your connection instance>);
}
}
This will enable you to do the following in your resource:
@GET
public Response getSomething(@Context Connection connection) {
// connection will be automatically injected in the connection
variable by jersey)
// do whatever you need with the connection class
}
You can look at the source of the SingletonTypeInjectableProvider if you
want to come up with something a bit more customized (do a lazy
initialization of the connection, etc.) and implement InjectableProvider
and Injectable interfaces without using this helper class
(
http://java.net/projects/jersey/sources/svn/content/trunk/jersey/jersey-core/src/main/java/com/sun/jersey/spi/inject/SingletonTypeInjectableProvider.java).
Martin
On 23.6.2011 17:52, juminoz wrote:
> Martin,
>
> Here's what I'm trying to do.
>
> 1) Initialize connection to datasource at start up. This could be a database
> or even connecting to JMS.
> 2) For every request to the servlet, it should reuse these connection
> resources rather than creating a new one.
>
> For a regular servlet, you can do all these in init method and store the
> reference in memory. For Jersey servlet, this doesn't seem to be an option.
>
> Potentially, I can utilize web server connection pool for these resource and
> grab connection from the pool instead of connecting every time
> (authentication is very expensive), but I would expect to be able to do
> similar thing without having to use connection pool.
>
> Why isn't the resource create once and reused? Why should the resource class
> constructor be called every time. I know REST is supposed to be stateless
> and all, but why go through a potentially expensive call to create a new
> resource for each call to the servlet. If a resource must be created per
> request then what would be the best way to store some connection objects
> without resorting for connection pool provided by web/app server?
>
> Thanks,
> Jack
>
> --
> View this message in context: http://jersey.576304.n2.nabble.com/Servlet-Init-For-Jersey-REST-Service-tp6507144p6508806.html
> Sent from the Jersey mailing list archive at Nabble.com.