users@jersey.java.net

[Jersey] Re: UriInfo injection at resource initialization time

From: Martin Matula <martin.matula_at_oracle.com>
Date: Wed, 09 Mar 2011 10:57:38 +0100

Hi Martynas,
UriInfo is specific to the current request (has some properties that
provide info for the specific request). You can't inject such thing to
an instance variable of a singleton. Does not make sense.
I believe UriBuilder.fromResource(TestResource.class).build() is what
you are looking for.
Martin

On 9.3.2011 2:39, Martynas Jusevicius wrote:
> Hey list,
>
> I'm new here and would like to start with a question :)
>
> I have Resource classes implementing JAX-RS, however I also want to
> combine it with RDF using Jena API.
> Each Resource should have a reference to Individual (RDF resource) -
> and they share the same absolute URI.
> This is a root Resource class:
>
> @Path("")
> @Singleton
> public class TestResource
> {
> private Individual individual = null;
>
> ...
> }
>
> This means Individual has to be initiated at some point, and at that
> point the Resource needs to know its URI to be able to look up
> Individual in the RDF model.
>
> What I've tried (the code goes inside the TestResource defined above):
>
> 1. Injected class field
>
> @Context UriInfo uriInfo;
>
> public TestResource()
> {
> System.out.println("TestResource.uriInfo: " + uriInfo);
> }
>
> Doesn't work - returns null
>
> 2. Injected constructor parameter
>
> public TestResource(@Context UriInfo uriInfo)
> {
> System.out.println("TestResource(uriInfo): " + uriInfo);
> }
>
> Doesn't work - I get
> java.lang.IllegalStateException
> com.sun.jersey.server.impl.ThreadLocalHttpContext.getUriInfo
> as described in
> http://jersey.576304.n2.nabble.com/injecting-UriInfo-in-constructor-td4510740.html
> Same message suggests "access the reference when a request is in
> scope" -- but this is not good enough.
>
> However constructor param is used in JAX-RS tutorial:
> http://wikis.sun.com/display/Jersey/Overview+of+JAX-RS+1.0+Features#OverviewofJAX-RS1.0Features-ConditionalGETsandReturning304%28NotModified%29Responses
>
> 3. @PostConstruct method
>
> @PostConstruct
> public void init()
> {
> System.out.println("@PostConstruct UriInfo: " + uriInfo);
> }
>
> Doesn't work - never gets executed
>
> Am I missing something? It seems as such a common use case - why isn't
> there a simple solution?
> I see no reason why root Resources with static @Path could not have
> access to their UriInfo at any time - their URI is known right from
> the start?
> And why does @PostConstruct not work? I'm running Tomcat 6.0.26.
>
> Thanks,
>
> Martynas
> semantic-web.dk