users@jersey.java.net

[Jersey] Re: Init some data when my resource is called

From: Christopher Currie <christopher_at_currie.com>
Date: Mon, 28 Nov 2011 10:49:22 -0800

On Mon, Nov 28, 2011 at 6:19 AM, tmp <le_tmp_at_gmx.de> wrote:
> hello!
>
> when i create a normal java app the main class like like this:
>
> public static void main(String[] args) {
>                .... SOME CODE ...
> }
>
> there I can put my initial code (for example logger configuration ).
>
> How can I achieve that in a resource? There I don't have a main method, but
> I need to init some data everytime this resource is called.
>
> Do I have to create something like an init-function and call it from every
> method of that resource or is there a better way?

Jersey root resource objects are created "per-request." They are not
singletons like Servlets. The class constructor will be called before
every request, and is the appropriate place to put per-request
operations.

However, if you're using this to initialize data that is always the
same for every request, you might want to consider another option,
such as writing a ContextResolver that can initialize the data once
and make it available to root resources.

Christopher