如何设置aop MethodInterceptor
以使用Jersey资源?
以下是我在this文档后尝试过的内容:
第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;
}
}
第2步 - 注册服务
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
。请参阅this question,了解我无法使用其中一个来处理安全性的原因。
答案 0 :(得分:5)
我认为您可能希望改为添加到configure()语句中而不是调用register(MyInterceptionService.class):
bind(MyInterceptionService.class).to(InterceptionService.class).in(Singleton.class)
我不确定它会起作用,因为我自己没有尝试过,所以你的结果可能会有所不同lol