users@jersey.java.net

[Jersey] method injection with guice

From: Christopher Piggott <cpiggott_at_gmail.com>
Date: Tue, 19 Jul 2011 18:09:39 -0400

Hi,

I was reading this:

http://jersey.java.net/nonav/apidocs/1.8/contribs/jersey-guice/com/sun/jersey/guice/spi/container/servlet/package-summary.html

and way at the bottom (last few lines) it gave me the idea that method
injection should work. So, first I created a baseline:

@Path("/")
@RequestScoped
public class Test {
        private final String greeting;

        @Inject
        public Test(@Named("greeting") String greeting) {
                this.greeting = greeting;
        }

        @GET
        @Produces({MediaType.TEXT_PLAIN})
        @Path("test")
        public String get() {
                System.out.println("Returning a greeting " + greeting);
                return greeting;
        }
}


and bound the string to "Hi Chris" in the module. Results were total
success, and the console said:
    Returning a greeting Hi Chris
as expected.

Then, I thought let's try method injection, so I changed the class to this:

@Path("/")
@RequestScoped
public class Test {
        @GET
        @Produces({MediaType.TEXT_PLAIN})
        @Path("test")
        @Inject public String get(@Named("greeting") String greeting) {
                System.out.println("Returning a greeting " + greeting);
                return greeting;
        }
}

Now, I get a blank page back. The actual HTTP response says this:

    HTTP/1.1 200 OK
    Content-Type: text/plain
    Content-Length: 0
    Server: Jetty(6.1.10)

but the interesting thing is the console says:

    Returning a greeting Hi Chris
    Returning a greeting
    Returning a greeting Hi Chris

So it's trying ... but it called my resource method three times; twice
properly injected, once not... and a zero-content-length response.

I'm not sure quite what to make of this. Should this work?

--Chris