jax-rs在ContainerRequestFilter和ReaderInterceptor之间共享信息 [英] jax-rs share information between ContainerRequestFilter and ReaderInterceptor

查看:106
本文介绍了jax-rs在ContainerRequestFilter和ReaderInterceptor之间共享信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jax-rs,并且在Filters中进行了一些逻辑处理,然后我想在ContainerRequestFilter(过滤器)和ReaderInterceptor(拦截器)之间共享信息.

I'm using Jax-rs, and I'm doing some logic in the Filters, and then I would like to share information between ContainerRequestFilter(Filter) and ReaderInterceptor(Interceptor).

通过set/getProperties我可以看到在过滤器和拦截器之间是可能的,但是在过滤器和拦截器之间是不可能的.

I can see that between Filters and Interceptors is possible through the set/getProperties but between Filter and Interceptors is not possible.

是否知道是否还有其他机制?

Any idea if there's any other mechanism?.

致谢.

推荐答案

因此,与为此使用单独的服务相比,任何简单的方法只是将ContainerRequestContext注入到ReaderInterceptor中.我们需要将其作为 javax.inject.Provider 注入这样我们就可以懒惰地取回它.如果不这样做,就会遇到范围问题,因为拦截器本质上是单例,并且请求上下文是请求范围的(意味着为每个请求创建一个新的).

So any easier way than using a separate service for this is to simply inject the ContainerRequestContext into the ReaderInterceptor. We need to inject it as a javax.inject.Provider so that we can lazy retrieve it. If we don't do this, we will run into scoping issues, as the interceptor is inherently a singleton and the request context is request scoped (meaning a new one is created for each request).

public static class MyInterceptor implements ReaderInterceptor {
    private final javax.inject.Provider<ContainerRequestContext> requestProvider;

    @Inject
    public MyInterceptor(javax.inject.Provider<ContainerRequestContext> requestProvider) {
        this.requestProvider = requestProvider;
    }

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException {
        ContainerRequestContext request = requestProvider.get();
        String prop = (String) request.getProperty("SomeProp");
    }
}

使用javax.inject.Provider,我们通过调用get()获得实际服务.因为我们使用的是Provider,所以将从请求范围内的上下文中检索服务,这意味着实例将与请求绑定.

With the javax.inject.Provider, we get the actual service by calling get(). Because we are using Provider, the service will be retrieved from a request scoped context, meaning that the instance will be tied to the request.

1.参见使用泽西岛以获取更多信息.

1. See Request Scoped Injection into a Singleton with Jersey for more information.

这篇关于jax-rs在ContainerRequestFilter和ReaderInterceptor之间共享信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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