我有一个注释@MagicAnnotation
,它允许我将参数注入我的资源。实施如下:
@Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MagicAnnotation {
}
public class MagicResolver extends ParamInjectionResolver<MagicAnnotation> {
public MagicResolver() {
super(MagicProvider.class);
}
}
public class MagicProvider extends AbstractValueFactoryProvider {
@Inject
public MagicProvider(final MultivaluedParameterExtractorProvider provider, final ServiceLocator locator) {
super(provider, locator, Parameter.Source.UNKNOWN);
}
@Override
protected Factory<?> createValueFactory(final Parameter parameter) {
return new MagicFactory();
}
}
public class MagicFactory extends AbstractContainerRequestValueFactory<String> {
@Context
private HttpServletRequest request;
@Override
public String provide() {
return request.getParameter("value");
}
}
在我的JAX-RS配置中,我将binder注册如下:
public class MagicBinder extends AbstractBinder {
@Override
protected void configure() {
bind(MagicProvider.class).to(ValueFactoryProvider.class).in(Singleton.class);
bind(MagicResolver.class).to(new TypeLiteral<InjectionResolver<MagicAnnotation>>() {
}).in(Singleton.class);
}
}
register(new MagicBinder());
这很有效。用法示例:
@Path("/magic")
public class SomeTest {
@MagicAnnotation
private String magic;
@GET
public Response test() {
return Response.ok(magic).build();
}
}
现在,我想在@MagicAnnotation
内使用ContainerRequestFilter
。我试着如下:
@Provider
public class MagicFilter implements ContainerRequestFilter {
@MagicAnnotation
private String magic;
@Override
public void filter(final ContainerRequestContext context) {
if (!"secret".equals(magic)) {
throw new NotFoundException();
}
}
}
这在初始化期间提供以下内容:
java.lang.IllegalStateException: Not inside a request scope
经过一些调试后,我发现在HttpServletRequest
中注入MagicFactory
是个问题。我猜HttpServletRequest
是一个请求上下文类(每个HTTP请求都不同),HK2无法为该类创建代理。难道HttpServletRequest
本身不是代理人吗?
我怎样才能解决这个问题?
答案 0 :(得分:0)
难道HttpServletRequest本身已经是代理吗?
是的,但是因为你试图将魔术注释目标注入过滤器(这是在应用程序启动时实例化的单例),所以调用工厂的provide()
方法,调用HttpServletRequest
。而且因为在启动时没有请求,所以你得到的不是最新的范围&#34;错误。
最简单的解决方法是使用javax.inject.Provider
懒惰地检索注入的对象。这样,在您通过调用Provider#get()
请求对象之前,不会调用工厂。
@Provider
public class MagicFilter implements ContainerRequestFilter {
@MagicAnnotation
private Provider<String> magic;
@Override
public void filter(final ContainerRequestContext context) {
// Provider#get()
if (!"secret".equals(magic.get())) {
throw new NotFoundException();
}
}
}
好的,所以上面的解决方案不会起作用。似乎即使使用Provider
,仍然会调用工厂。
我们需要做的是将magic
值设为代理。但是String不能被代理,所以我做了一个包装器。
public class MagicWrapper {
private String value;
/* need to proxy */
public MagicWrapper() {
}
public MagicWrapper(String value) {
this.value = value;
}
public String get() {
return this.value;
}
}
现在进行一些重组。我们应该首先理解的是所需的组件。您当前用于参数注入的模式是Jersey源中用于处理@PathParam
和@QueryParam
等参数的参数注入的模式。
用作该基础结构一部分的类是您正在使用的AbstractValueFactoryProvider
和ParamInjectionResolver
。但是这些类只是泽西岛用来保持DRY的真正的辅助类,因为要注入许多不同类型的参数。但是这些类只是为处理这个用例而需要实现的主要合同的扩展,即ValueFactoryProvider
和InjectResolver
。因此,我们可以通过直接实施这些合同来重构我们的用例,而不是使用Jersey&#34; helper&#34;基础设施。这允许我们在需要的地方创建代理。
要为我们的MagicWrapper
创建代理,我们只需在Factory
中为其配置AbstractBinder
作为代理
@Override
public void configure() {
bindFactory(MagicWrapperFactory.class)
.to(MagicWrapper.class)
.proxy(true)
.proxyForSameScope(false)
.in(RequestScoped.class);
}
对proxy
的调用使对象可以代理,对proxyForSameScope(false)
的调用确保当它在请求范围内时,它是实际对象,而不是代理。在这里真的没什么区别。只有真正重要的是调用proxy()
。
现在要处理自定义注释注入,我们需要一个InjectionResolver
。这是它的工作。
public class MagicInjectionResolver implements InjectionResolver<MagicAnnotation> {
@Inject @Named(InjectionResolver.SYSTEM_RESOLVER_NAME)
private InjectionResolver<Inject> systemResolver;
@Override
public Object resolve(Injectee injectee, ServiceHandle<?> handle) {
if (injectee.getRequiredType() == MagicWrapper.class) {
return systemResolver.resolve(injectee, handle);
}
return null;
}
@Override
public boolean isConstructorParameterIndicator() { return false; }
@Override
public boolean isMethodParameterIndicator() { return true; }
}
如上所述,您当前使用的ParamInjectionResolver
只是InjectionResolver
的一种实现,它更加简化,但在这种情况下无法使用。所以我们自己实现它。我们除了检查类型以外我们什么都不做,所以我们只处理MagicWrapper
的注入。然后我们将工作委托给系统InjectionResolver
。
现在我们需要Jersey用于方法参数注入的组件,即ValueFactoryProvider
。
public class MagicValueFactoryProvider implements ValueFactoryProvider {
@Inject
private ServiceLocator locator;
@Override
public Factory<?> getValueFactory(Parameter parameter) {
if (parameter.isAnnotationPresent((MagicAnnotation.class))) {
final MagicWrapperFactory factory = new MagicWrapperFactory();
locator.inject(factory);
return factory;
}
return null;
}
@Override
public PriorityType getPriority() {
return Priority.NORMAL;
}
}
我们刚刚回到工厂,就像你在AbstractValueFactoryProvider
中所做的那样。唯一的区别是,我们需要明确地注入它,以便它获得HttpServletRequest
。这与泽西在AbstractValueFactoryProvider
中所做的一样。
就是这样。以下是使用Jersey Test Framework的完整示例。像任何其他JUnit测试一样运行它。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.api.Injectee;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.process.internal.RequestScoped;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.model.Parameter;
import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
/**
* See http://stackoverflow.com/q/39411704/2587435
*
* Run like any other JUnit test. Only one require dependency
* <dependency>
* <groupId>org.glassfish.jersey.test-framework.providers</groupId>
* <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
* <version>${jersey2.version}</version>
* <scope>test</scope>
* </dependency>
*
* @author Paul Samsotha
*/
public class InjectionTest extends JerseyTest {
@Path("test")
public static class TestResource {
@GET
public String get(@MagicAnnotation MagicWrapper magic) {
return magic.get();
}
}
@Provider
public static class MagicFilter implements ContainerResponseFilter {
@MagicAnnotation
private MagicWrapper magic;
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
response.getHeaders().add("X-Magic-Header", magic.get());
}
}
@Override
public ResourceConfig configure() {
return new ResourceConfig()
.register(TestResource.class)
.register(MagicFilter.class)
.register(new LoggingFilter(Logger.getAnonymousLogger(), true))
.register(new AbstractBinder() {
@Override
public void configure() {
bindFactory(MagicWrapperFactory.class)
.to(MagicWrapper.class)
.proxy(true)
.proxyForSameScope(false)
.in(RequestScoped.class);
bind(MagicInjectionResolver.class)
.to(new TypeLiteral<InjectionResolver<MagicAnnotation>>(){})
.in(Singleton.class);
bind(MagicValueFactoryProvider.class)
.to(ValueFactoryProvider.class)
.in(Singleton.class);
}
});
}
@Override
public TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
@Override
public DeploymentContext configureDeployment() {
return ServletDeploymentContext.forServlet(new ServletContainer(configure())).build();
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.FIELD})
public static @interface MagicAnnotation {
}
public static class MagicWrapper {
private String value;
/* need to proxy */
public MagicWrapper() {
}
public MagicWrapper(String value) {
this.value = value;
}
public String get() {
return this.value;
}
}
public static class MagicWrapperFactory implements Factory<MagicWrapper> {
@Context
private HttpServletRequest request;
@Override
public MagicWrapper provide() {
return new MagicWrapper(request.getParameter("value"));
}
@Override
public void dispose(MagicWrapper magic) {}
}
public static class MagicValueFactoryProvider implements ValueFactoryProvider {
@Inject
private ServiceLocator locator;
@Override
public Factory<?> getValueFactory(Parameter parameter) {
if (parameter.isAnnotationPresent((MagicAnnotation.class))) {
final MagicWrapperFactory factory = new MagicWrapperFactory();
locator.inject(factory);
return factory;
}
return null;
}
@Override
public PriorityType getPriority() {
return Priority.NORMAL;
}
}
public static class MagicInjectionResolver implements InjectionResolver<MagicAnnotation> {
@Inject @Named(InjectionResolver.SYSTEM_RESOLVER_NAME)
private InjectionResolver<Inject> systemResolver;
@Override
public Object resolve(Injectee injectee, ServiceHandle<?> handle) {
if (injectee.getRequiredType() == MagicWrapper.class) {
return systemResolver.resolve(injectee, handle);
}
return null;
}
@Override
public boolean isConstructorParameterIndicator() { return false; }
@Override
public boolean isMethodParameterIndicator() { return true; }
}
@Test
public void testInjectionsOk() {
final Response response = target("test").queryParam("value", "HelloWorld")
.request().get();
assertEquals("HelloWorld", response.readEntity(String.class));
assertEquals("HelloWorld", response.getHeaderString("X-Magic-Header"));
}
}
另见:
InjectionResolver
的详情,请参阅here和here