如何在 Jersey 2.4 过滤器中获取资源注释? [英] How can I get resource annotations in a Jersey 2.4 filter?

查看:26
本文介绍了如何在 Jersey 2.4 过滤器中获取资源注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题和这个基本一样:如何在 Jersey ContainerResponseFilter 中获取资源注释.

My question is essentially the same as this one: How can I get resource annotations in a Jersey ContainerResponseFilter.

但我使用的是 Java Jersey 2.4 并且找不到 ResourceFilterFactory 或 ResourceFilter 类的任何迹象.文档也没有提到它们.它们是否已被弃用,或者它们真的隐藏得很好?如果它们已被弃用,我可以用什么代替?Jersey 2.4 和 2.5 现在有办法从 ContainerRequestFilter 获取资源注释吗?

But I'm using Java Jersey 2.4 and can't find any sign of the ResourceFilterFactory or ResourceFilter classes. The documentation also doesn't mention them. Have they been deprecated or are they just really well hidden? If they've been deprecated, what can I use instead? Is there now a way with Jersey 2.4 and 2.5 to get the resource annotations from a ContainerRequestFilter?

谢谢

推荐答案

如果您想根据资源方法/类上可用的注释修改请求的处理,那么我建议使用 DynamicFeature 来自 JAX-RS 2.0.使用 DynamicFeature 可以为可用资源方法的子集分配特定的提供者.例如,考虑我有一个资源类,如:

If you want to modify processing of a request based on annotations available on a resource method/class then I'd recommend using DynamicFeature from JAX-RS 2.0. Using DynamicFeatures you can assign specific providers for a subset of available resource methods. For example, consider I have a resource class like:

@Path("helloworld")
public class HelloWorldResource {

    @GET
    @Produces("text/plain")
    public String getHello() {
        return "Hello World!";
    }
}

我想分配一个 ContainerRequestFilter到它.我将创建:

And I'd like to assign a ContainerRequestFilter to it. I'll create:

@Provider
public class MyDynamicFeature implements DynamicFeature {

    @Override
    public void configure(final ResourceInfo resourceInfo, final FeatureContext context) {
        if ("HelloWorldResource".equals(resourceInfo.getResourceClass().getSimpleName())
                && "getHello".equals(resourceInfo.getResourceMethod().getName())) {
            context.register(MyContainerRequestFilter.class);
        }
    }
}

并且在注册之后(如果您'正在使用包扫描那么你不需要注册它,以防它有 @Provider 注释)MyContainerRequestFilter 将与你的资源方法相关联.

And after registration (if you're using package scanning then you don't need to register it in case it has @Provider annotation on it) MyContainerRequestFilter will be associated with your resource method.

另一方面,您始终可以注入 ResourceInfo在您的过滤器中(它不能用 @PreMatching 注释)并从中获取注释:

On the other hand you can always inject ResourceInfo in your filter (it can't be annotated with @PreMatching) and obtain the annotations from it:

@Provider
public class MyContainerRequestFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(final ContainerRequestContext requestContext) throws IOException {
        resourceInfo.getResourceMethod().getDeclaredAnnotations();
    }
}

这篇关于如何在 Jersey 2.4 过滤器中获取资源注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆