Java 带Jersey资源的HK2 MethodInterceptor
如何设置aopJava 带Jersey资源的HK2 MethodInterceptor,java,jersey,aop,jersey-2.0,hk2,Java,Jersey,Aop,Jersey 2.0,Hk2,如何设置aopMethodInterceptor以使用Jersey资源 以下是我尝试过的内容,包括以下文档: 步骤1-拦截服务 public class MyInterceptionService implements InterceptionService { private final Provider<AuthFilter> authFilterProvider; @Inject public HK2MethodInterceptionService(
MethodInterceptor
以使用Jersey资源
以下是我尝试过的内容,包括以下文档:
步骤1-拦截服务
public class MyInterceptionService implements InterceptionService
{
private final Provider<AuthFilter> authFilterProvider;
@Inject
public HK2MethodInterceptionService(Provider<AuthFilter> authFilterProvider)
{
this.authFilterProvider = authFilterProvider;
}
/**
* Match any class.
*/
@Override
public Filter getDescriptorFilter()
{
return BuilderHelper.allFilter();
}
/**
* Intercept all Jersey resource methods for security.
*/
@Override
@Nullable
public List<MethodInterceptor> getMethodInterceptors(final Method method)
{
// don't intercept methods with PermitAll
if (method.isAnnotationPresent(PermitAll.class))
{
return null;
}
return Collections.singletonList(new MethodInterceptor()
{
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable
{
if (!authFilterProvider.get().isAllowed(method))
{
throw new ForbiddenException();
}
return methodInvocation.proceed();
}
});
}
/**
* No constructor interception.
*/
@Override
@Nullable
public List<ConstructorInterceptor> getConstructorInterceptors(Constructor<?> constructor)
{
return null;
}
}
public class MyResourceConfig extends ResourceConfig
{
public MyResourceConfig()
{
packages("package.with.my.resources");
// UPDATE: answer is remove this line
register(MyInterceptionService.class);
register(new AbstractBinder()
{
@Override
protected void configure()
{
bind(AuthFilter.class).to(AuthFilter.class).in(Singleton.class);
// UPDATE: answer is add the following line
// bind(MyInterceptionService.class).to(InterceptionService.class).in(Singleton.class);
}
});
}
}
但是,这似乎不起作用,因为我的任何资源方法都没有被拦截。这可能是因为我使用了所有资源的@ManagedAsync
?有什么想法吗
另外,请不要建议使用
ContainerRequestFilter
。看看为什么我不能用它来处理安全问题 我认为与其调用register(MyInterceptionService.class),不如将其添加到configure()语句中:
bind(MyInterceptionService.class).to(InterceptionService.class).in(Singleton.class)
我不确定它是否会起作用,因为我自己还没有尝试过,所以你的结果可能会有所不同lol哦,好主意!我在configure()中也尝试过这样做,但我在(Singleton.class)中绑定了(MyInterceptionService.class),这肯定是错误的。现在就试试吧……这很管用!我不确定你是否读过我上面链接的另一个问题,但我现在在我的项目中有一个
AsyncContainerRequestFilter扩展了ContainerRequestFilter
,还有一个注册它们的通用方法,这让我非常兴奋:)要了解GUICE+jersey的更详细示例,请看这里哇,多棒的gr8页面。您介意我们从guice/hk2桥上的hk2文档中指出它吗?当然可以,请随意这样做。