繁体   English   中英

如何使ContainerRequestFilter过滤多个注释,但在Java中一次过滤1个?

[英]How make ContainerRequestFilter filter on multiple annotations, but 1 at a time in Java?

我创建了一个ContainerRequestFilter但是当我添加两个注释时,为了在任何方法上调用它,该方法需要两个注释。 我想要的是这个:

提供者:

@TypeA
@TypeB
@Provider
@Priority( Priorities.AUTHENTICATION )
public class AuthenticationFilter implements ContainerRequestFilter
{ ... }

一些被过滤的类:

@Path( "/test" )
public class TestStuff
{
    @POST
    @Produces( MediaType.APPLICATION_JSON )
    @Path( "auth" )
    @TypeA
    public Response login() { ... }

    @POST
    @Produces( MediaType.APPLICATION_JSON )
    @Path( "auth" )
    @TypeB
    public Response somethingElse() { ... }

}

但这不起作用。 它只有在我这样做时才有效:

@Path( "/test" )
public class TestStuff
{
    @POST
    @Produces( MediaType.APPLICATION_JSON )
    @Path( "auth" )
    @TypeA
    @TypeB
    public Response login() { ... }

    @POST
    @Produces( MediaType.APPLICATION_JSON )
    @Path( "auth" )
    @TypeA
    @TypeB
    public Response somethingElse() { ... }

}

如何在类型的“OR”上进行过滤匹配?

您可以使用动态绑定而不是名称 绑定 您只需要实现DyanamiCFeature ,并检查该方法是否具有注释,以确定是否应该为该方法注册过滤器。

public class AuthDynamicFeature implements DynamicFeature {

    @Override
    public void configure(ResourceInfo info, FeatureContext context) {
        Method method = info.getResourceMethod();
        if (method.isAnnotationPresent(TypeA.class)
            || method.isAnnotationPresent(TypeB.class)) {

            context.register(new AuthenticationFilter());
            // or context.register(AuthenticationFilter.class);
        }
    }
}

然后只需在应用程序中注册该功能。 或者,如果在功能上添加@Provider ,并且启用了包/类路径扫描,它将自动注册。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM