我目前正在尝试InjectableProvider
使用 Jersey 创建一个,但我无法让 Jersey 来接它。
@Provider
除了在实现上使用注释之外,我找不到任何关于其用法的真实示例,甚至找不到如何获取它。似乎在泽西岛写它的人在一些帖子中暗示这足以让它被捡起来。
我是否需要指定一些 SPI 服务文件,或者将其添加到某个工厂?
注意:我在 Glassfish 3.1 中运行,并使用 Spring 3.1。Spring 可能会以某种方式接管Provider
s 的自动加载,这似乎是合理的。但是,我只是不知道。无论如何,我都没有使用 Spring 来管理下面建议的 InjectableProvider,也没有尝试以其他方式添加它,这可能是我的问题。
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<T>
extends PerRequestTypeInjectableProvider<AttributeParam, T>
{
protected final Class<T> type;
public AbstractAttributeInjectableProvider(Class<T> type)
{
super(type);
this.type = type;
}
@Override
public Injectable<T> getInjectable(ComponentContext componentContext,
AttributeParam attributeParam)
{
return new AttributeInjectable<T>(type, attributeParam.value());
}
}
基本实现:
import javax.ws.rs.ext.Provider;
@Component // <- Spring Annotation
@Provider // <- Jersey Annotation
public class MyTypeAttributeInjectableProvider
extends AbstractAttributeInjectableProvider<MyType>
{
public MyTypeAttributeInjectableProvider()
{
super(MyType.class);
}
}
参考Annotation
:
@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();
}
更新:calvinkrishy 指出了我的想法的两个缺陷。
首先,我假设 Jersey@Provider
在被传统的 Jersey-Spring servlet 启动后将开始扫描 s com.sun.jersey.spi.spring.container.servlet.SpringServlet
:. 这大多是不正确的;它确实开始扫描,但它会查找具有注释的 Spring bean。
其次,我假设PerRequestTypeInjectableProvider
在每次传入请求时都会询问 anInjectable
来处理它控制的注释。这也是错误的。正如预期的PerRequestTypeInjectableProvider
那样,在启动时实例化了,但泽西岛随后立即要求Injectable
's 用给定的来处理给定的注释type
,它通过扫描它拥有的 Restful 服务来确定——此时——决定它管理(也就是说,所有这些)。
PerRequestTypeInjectableProvider
和之间的区别SingletonTypeInjectableProvider
似乎是结果Injectable
要么包含值而不为它工作(单例),要么每次都查找它的值(每个请求),从而使每个请求的值都可以更改。
这迫使我在我的AttributeInjectable
(下面的代码)中做一些额外的工作,而不是像我计划的那样传递一些对象,以避免提供AttributeInjectable
额外的知识,这给我的计划带来了一个较小的影响。
public class AttributeInjectable<T> implements Injectable<T>
{
/**
* The type of data that is being requested.
*/
private final Class<T> 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<T> 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}.
* <p />
* 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();
}
}
我希望能够从 中传递HttpServletRequest
,Provider
但AttributeInjectable
仅针对每个唯一的注释/类型进行实例化。因为我不能这样做,所以我执行每个值查找,它使用 Spring 的RequestContextFilter
单例,它提供了一种ThreadLocal
安全检索HttpServletRequest
(以及与当前请求相关的其他内容)的机制。
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>
org.springframework.web.filter.RequestContextFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/path/that/i/wanted/*</url-pattern>
</filter-mapping>
结果确实有效,并且它使代码更具可读性,而无需强制各种服务扩展基类只是为了隐藏 的用法@Context HttpServletRequest request
,然后通过一些辅助方法将其用于访问上述属性。
然后你可以按照以下方式做一些事情:
@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
}
}
这变得非常方便,因为我使用 Servlet 过滤器来确保用户在传递数据之前具有访问服务的适当权限,然后我可以解析传入的数据(或加载它,或其他)并将其转储到属性中要加载。
如果您不想要上述Provider
方法,并且想要用于访问属性的基类,那么您可以这样做:
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 <T> T getAttribute(String name, Class<T> 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
}
}
UPDATE2:我考虑了我AbstractAttributeInjectableProvider
的. 提供一个非实现要容易得多,它在每个请求时都被告知其类型 () ,从而避免了一堆只为您提供类型的构造函数实现。这也避免了必须为要与注释一起使用的每种类型编写代码。AttributeInjectable
Class<T>
AttributeParam
abstract
Class<T>
AttributeParam
AttributeParam
@Component
@Provider
public class AttributeParamInjectableProvider
implements InjectableProvider<AttributeParam, Type>
{
/**
* {@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<?> getInjectable(ComponentContext context,
AttributeParam parameter,
Type type)
{
AttributeInjectable<?> injectable = null;
// as long as it's something that we can work with...
if (type instanceof Class)
{
injectable = getInjectable((Class<?>)type, parameter);
}
return injectable;
}
/**
* Create a new {@link AttributeInjectable} for the given {@code type} and
* {@code parameter}.
* <p />
* 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 <T> The type of data being accessed by the {@code param}.
* @return Never {@code null}.
*/
protected <T> AttributeInjectable<T> getInjectable(Class<T> type,
AttributeParam parameter)
{
return new AttributeInjectable<T>(type, parameter.value());
}
}
注意:每个Injectable
都在启动时实例化一次,而不是每个请求,但在每个传入请求时都会调用它们。