Skip to content

Instantly share code, notes, and snippets.

@codyaray
Created January 3, 2013 06:57
Show Gist options
  • Save codyaray/4441355 to your computer and use it in GitHub Desktop.
Save codyaray/4441355 to your computer and use it in GitHub Desktop.
Simplified AbstractInjectableProvider for building RESTful web services with Jersey using Guava to find the generic parameter types. See http://codyaray.com/2013/01/finding-generic-type-parameters-with-guava for details.
package com.mydomain.myapp.resources;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import javax.ws.rs.core.Context;
import com.google.common.reflect.TypeToken;
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;
/**
* Abstract class for making Jersey injectable providers.
*
* @param <T> the type of the injectable value.
* @author codyaray
* @since 2/01/2012
* @see http://codahale.com/what-makes-jersey-interesting-injection-providers/
*/
public abstract class AbstractInjectableProvider<T> extends AbstractHttpContextInjectable<T>
implements InjectableProvider<Context, Type> {
@SuppressWarnings("serial")
private final TypeToken<T> typeToken = new TypeToken<T>(getClass()) { };
private final Type type = typeToken.getType();
@Override
public Injectable<T> getInjectable(ComponentContext componentContext, Context context, Type type) {
return type.equals(this.type) ? getInjectable(componentContext, context) : null;
}
protected Injectable<T> getInjectable(ComponentContext componentContext, Context context) {
return this;
}
@Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment