gpt4 book ai didi

java - 在 JAXRS 中,仅将容器请求拦截器应用于特定提供者

转载 作者:行者123 更新时间:2023-12-02 11:56:51 27 4
gpt4 key购买 nike

使用 JAXRS-2.0(特别是 Jersey 2.2),我试图将请求拦截器应用于特定的资源提供程序类(位于第 3 方库中),但我显然做错了。我收到以下错误 - 我对其原因有点困惑。最终效果是,针对每个提供者(而不是 1 个提供者)的每个请求都会调用拦截器。这是错误:

2017-11-26 10:43:51.061 [localhost-startStop-1][WARN][o.g.j.server.model.ResourceMethodConfig] - The given contract (interface javax.ws.rs.container.DynamicFeature) of class com.idfconnect.XYZ provider cannot be bound to a resource method.

拦截器类定义为:

@Provider
public class XYZ implements WriterInterceptor, DynamicFeature {

在我的 ResourceConfig 中,我正在为特定提供程序注册拦截器,如下所示(我怀疑这是我误入歧途的地方):

@ApplicationPath("service")
public class MyApp extends ResourceConfig {
public MyApp() {
ResourceConfig rc = register(SomeThirdPartyResource.class);
rc.register(XYZ.class);
...

有人可以帮我弄清楚如何将拦截器仅绑定(bind)到 SomeThirdPartyResource 类吗?

最佳答案

您不应该让您的提供商实现 DynamicFeature 。这可能是警告的原因。你正在尝试注册拦截器,它也是一个 DynamicFeature , Jersey 告诉你 DynamicFeature不是应该注册到方法的东西。

您应该为DynamicFeature创建一个单独的类并在 configure 内检查您想要将提供程序附加到的资源(使用 ResourceInfo ,然后相应地注册它。例如

class XYZ implements DynamicFeature {
@Override
public void configure(ResourceInfo info, FeatureContext ctx) {
if (info.getResourceClass().equals(ThirdPartyResource.class) {
ctx.register(YourWriterImplementation.class);
// or
ctx.register(new YourWriterImplementation());
}
}
}

您获得拦截器命中的所有资源的原因是因为您正在使用 ResourceConfig 注册拦截器。这将附加所有资源。您只想注册DynamicFeature并让它确定要绑定(bind)到哪个资源。

关于java - 在 JAXRS 中,仅将容器请求拦截器应用于特定提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47545788/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com