title: Jersey: InjectableProvider not picked up - Spring
body: <p>I am currently trying to create an <code>InjectableProvider</code> with Jersey, but I cannot get Jersey to pick it up.</p>
  
  <p>I cannot find any real examples of its usage, or even how to get it picked up besides using the <code>@Provider</code> annotation on the implementation. The person that seemingly wrote it within Jersey implied in some posts that this is enough to have it picked up.</p>
  
  <p>Do I need to specify some SPI service file, or add it to some factory somewhere?</p>
  
  <p>Note: I am running within Glassfish 3.1, and using Spring 3.1. It seems reasonable that Spring may be somehow taking over for the automatic loading of the <code>Provider</code>s. However, I just don't know. I am not using Spring in anyway to manage the suggested InjectableProvider below, nor am I trying to add it in some other way, which may-well be my problem.</p>
  
  <pre><code>import com.sun.jersey.core.spi.component.ComponentContext;
  import com.sun.jersey.spi.inject.Injectable;
  import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider;
  
  public abstract class AbstractAttributeInjectableProvider&lt;T&gt;
          extends PerRequestTypeInjectableProvider&lt;AttributeParam, T&gt;
  {
      protected final Class&lt;T&gt; type;
  
      public AbstractAttributeInjectableProvider(Class&lt;T&gt; type)
      {
          super(type);
  
          this.type = type;
      }
  
      @Override
      public Injectable&lt;T&gt; getInjectable(ComponentContext componentContext,
                                         AttributeParam attributeParam)
      {
          return new AttributeInjectable&lt;T&gt;(type, attributeParam.value());
      }
  }
  </code></pre>
  
  <p>Basic Implementation:</p>
  
  <pre><code>import javax.ws.rs.ext.Provider;
  
  @Component // &lt;- Spring Annotation
  @Provider  // &lt;- Jersey Annotation
  public class MyTypeAttributeInjectableProvider
          extends AbstractAttributeInjectableProvider&lt;MyType&gt;
  {
      public MyTypeAttributeInjectableProvider()
      {
          super(MyType.class);
      }
  }
  </code></pre>
  
  <p>Reference <code>Annotation</code>:</p>
  
  <pre><code>@Target({ElementType.FIELD, ElementType.PARAMETER})
  @Retention(RetentionPolicy.RUNTIME)
  @Documented
  public @interface AttributeParam
  {
      /**
       * The value is the name to request as an attribute from an {@link
       * HttpContext}'s {@link HttpServletRequest}.
       * @return Never {@code null}. Should never be blank.
       */
      String value();
  }
  </code></pre>
  
  <p>Reference <a href="http://jersey.576304.n2.nabble.com/Injected-into-hell-td680228.html" rel="noreferrer">link from Jersey developer</a>.</p>
  
  <hr>
  
  <p><strong>UPDATE</strong>: calvinkrishy pointed out two flaws to my thinking.</p>
  
  <p>First, I assumed that Jersey was going to kick off scanning for <code>@Provider</code>s after being kicked off by the traditional Jersey-Spring servlet: <code>com.sun.jersey.spi.spring.container.servlet.SpringServlet</code>. This was mostly incorrect; it does start scanning, but it looks for Spring beans that have the annotation.</p>
  
  <p>Second, I assumed that the <code>PerRequestTypeInjectableProvider</code> would be asked upon each incoming request for an <code>Injectable</code> to handle the annotation that it controls. This too was wrong. The <code>PerRequestTypeInjectableProvider</code> is instantiated upon startup, as expected, but Jersey then immediately asks for <code>Injectable</code>'s to handle the given annotation with the given <code>type</code>, which it determines by scanning the Restful Services that it has--at this point--decided that it manages (which is to say, all of them).</p>
  
  <p>The difference between the <code>PerRequestTypeInjectableProvider</code> and <code>SingletonTypeInjectableProvider</code> seems to be that the resulting <code>Injectable</code> either contains the value without working for it (singleton), or it looks it up each time for the value (per request), thus enabling the value to change per request.</p>
  
  <p>This threw a smaller wrench into my plans by forcing me to do some extra work in my <code>AttributeInjectable</code> (code below) rather than passing in some objects, as I had planned, to avoid giving the <code>AttributeInjectable</code> extra knowledge.</p>
  
  <pre><code>public class AttributeInjectable&lt;T&gt; implements Injectable&lt;T&gt;
  {
      /**
       * The type of data that is being requested.
       */
      private final Class&lt;T&gt; type;
      /**
       * The name to extract from the {@link HttpServletRequest} attributes.
       */
      private final String name;
  
      /**
       * Converts the attribute with the given {@code name} into the {@code type}.
       * @param type The type of data being retrieved
       * @param name The name being retrieved.
       * @throws IllegalArgumentException if any parameter is {@code null}.
       */
      public AttributeInjectable(Class&lt;T&gt; type, String name)
      {
          // check for null
  
          // required
          this.type = type;
          this.name = name;
      }
  
      /**
       * Look up the requested value.
       * @return {@code null} if the attribute does not exist or if it is not the
       *         appropriate {@link Class type}.
       *         &lt;p /&gt;
       *         Note: Jersey most likely will fail if the value is {@code null}.
       * @throws NullPointerException if {@link HttpServletRequest} is unset.
       * @see #getRequest()
       */
      @Override
      public T getValue()
      {
          T value = null;
          Object object = getRequest().getAttribute(name);
  
          if (type.isInstance(object))
          {
              value = type.cast(object);
          }
  
          return value;
      }
  
      /**
       * Get the current {@link HttpServletRequest} [hopefully] being made
       * containing the {@link HttpServletRequest#getAttribute(String) attribute}.
       * @throws NullPointerException if the Servlet Filter for the {@link
       *                              RequestContextHolder} is not setup
       *                              appropriately.
       * @see org.springframework.web.filter.RequestContextFilter
       */
      protected HttpServletRequest getRequest()
      {
          // get the request from the Spring Context Holder (this is done for
          //  every request by a filter)
          ServletRequestAttributes attributes =
              (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
  
          return attributes.getRequest();
      }
  }
  </code></pre>
  
  <p>I was hoping to be able to pass in the <code>HttpServletRequest</code> from the <code>Provider</code>, but the <code>AttributeInjectable</code> is only instantiated per unique annotation/type. As I cannot do that, I do that per value lookup, which uses Spring's <code>RequestContextFilter</code> singleton, which provides a <code>ThreadLocal</code> mechanism for safely retrieving the <code>HttpServletRequest</code> (among other things related to the current request).</p>
  
  <pre><code>&lt;filter&gt;
      &lt;filter-name&gt;requestContextFilter&lt;/filter-name&gt;
      &lt;filter-class&gt;
          org.springframework.web.filter.RequestContextFilter
      &lt;/filter-class&gt;
  &lt;/filter&gt;
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;requestContextFilter&lt;/filter-name&gt;
      &lt;url-pattern&gt;/path/that/i/wanted/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  </code></pre>
  
  <p>The result does work, and it makes the code much more readable without forcing various services to extend a base class just to hide the usage of <code>@Context HttpServletRequest request</code>, which is then used to access the attributes as done above through some helper method.</p>
  
  <p>Then you can do something along the lines of this:</p>
  
  <pre><code>@Path("my/path/to")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.TEXT_PLAIN)
  public interface MyService
  {
      @Path("service1")
      @POST
      Response postData(@AttributeParam("some.name") MyType data);
  
      @Path("service2")
      @POST
      Response postOtherData(@AttributeParam("other.name") MyOtherType data);
  }
  
  @Component // Spring
  public class MyServiceBean implements MyService
  {
      @Override
      public Response postData(MyType data)
      {
          // interact with data
      }
  
      @Override
      public Response postOtherData(MyOtherType data)
      {
          // interact with data
      }
  }
  </code></pre>
  
  <p>This becomes very convenient as I use a Servlet Filter to ensure that the user has the appropriate privileges to access the service before passing the data, and then I can parse the incoming data (or load it, or whatever) and dump it into the attribute to be loaded.</p>
  
  <p>If you don't want the above <code>Provider</code> approach, and you want the base class for accessing the attributes, then here you go:</p>
  
  <pre><code>public class RequestContextBean
  {
      /**
       * The current request from the user.
       */
      @Context
      protected HttpServletRequest request;
  
      /**
       * Get the attribute associated with the current {@link HttpServletRequest}.
       * @param name The attribute name.
       * @param type The expected type of the attribute.
       * @return {@code null} if the attribute does not exist, or if it does not
       *         match the {@code type}. Otherwise the appropriately casted
       *         attribute.
       * @throws NullPointerException if {@code type} is {@code null}.
       */
      public &lt;T&gt; T getAttribute(String name, Class&lt;T&gt; type)
      {
          T value = null;
          Object attribute = request.getAttribute(name);
  
          if (type.isInstance(attribute))
          {
              value = type.cast(attribute);
          }
  
          return value;
      }
  }
  
  @Path("my/path/to")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.TEXT_PLAIN)
  public interface MyService
  {
      @Path("service1")
      @POST
      Response postData();
  
      @Path("service2")
      @POST
      Response postOtherData();
  }
  
  @Component
  public class MyServiceBean extends RequestContextBean implements MyService
  {
      @Override
      public Response postData()
      {
          MyType data = getAttribute("some.name", MyType.class);
          // interact with data
      }
  
      @Override
      Response postOtherData()
      {
          MyOtherType data = getAttribute("other.name", MyOtherType.class);
          // interact with data
      }
  }
  </code></pre>
  
  <hr>
  
  <p><strong>UPDATE2</strong>: I thought about my implementation of <code>AbstractAttributeInjectableProvider</code>, which is itself a generic class that only exists to provide <code>AttributeInjectable</code>'s for a given type, <code>Class&lt;T&gt;</code> and the supplied <code>AttributeParam</code>. It's far easier to provide a non-<code>abstract</code> implementation that is told its type (<code>Class&lt;T&gt;</code>) with each requested <code>AttributeParam</code>, thus avoiding a bunch of constructor-only implementations providing the type for you. This also avoids having to write code for every single type that you want to use with the <code>AttributeParam</code> annotation.</p>
  
  <pre><code>@Component
  @Provider
  public class AttributeParamInjectableProvider
          implements InjectableProvider&lt;AttributeParam, Type&gt;
  {
      /**
       * {@inheritDoc}
       * @return Always {@link ComponentScope#PerRequest}.
       */
      @Override
      public ComponentScope getScope()
      {
          return ComponentScope.PerRequest;
      }
  
      /**
       * Get an {@link AttributeInjectable} to inject the {@code parameter} for
       * the given {@code type}.
       * @param context Unused.
       * @param parameter The requested parameter
       * @param type The type of data to be returned.
       * @return {@code null} if {@code type} is not a {@link Class}. Otherwise
       *         an {@link AttributeInjectable}.
       */
      @Override
      public AttributeInjectable&lt;?&gt; getInjectable(ComponentContext context,
                                                  AttributeParam parameter,
                                                  Type type)
      {
          AttributeInjectable&lt;?&gt; injectable = null;
  
          // as long as it's something that we can work with...
          if (type instanceof Class)
          {
              injectable = getInjectable((Class&lt;?&gt;)type, parameter);
          }
  
          return injectable;
      }
  
      /**
       * Create a new {@link AttributeInjectable} for the given {@code type} and
       * {@code parameter}.
       * &lt;p /&gt;
       * This is provided to avoid the support for generics without the need for
       * {@code SuppressWarnings} (avoided via indirection).
       * @param type The type of data to be returned.
       * @param parameter The requested parameter
       * @param &lt;T&gt; The type of data being accessed by the {@code param}.
       * @return Never {@code null}.
       */
      protected &lt;T&gt; AttributeInjectable&lt;T&gt; getInjectable(Class&lt;T&gt; type,
                                                         AttributeParam parameter)
      {
          return new AttributeInjectable&lt;T&gt;(type, parameter.value());
      }
  }
  </code></pre>
  
  <p>Note: each <code>Injectable</code> is instantiated once at startup rather than per request, but they are invoked upon each incoming request.</p>