简体   繁体   English

在 Jersey 2 中调用代理对象的包私有方法的奇怪行为

[英]Strange behavior calling package-private method of proxied object in Jersey 2

Following class下课

public class MaskHolder {

    private Mask mask;
    private UUID id = UUID.randomUUID()

    void store() {
        System.out.println(id);
    }

    public void get() {
        System.out.println(id);
    }

}

is bound to HK2 like this像这样绑定到HK2

bind(MaskHolder.class).to(MaskHolder.class)
            .proxy(true).proxyForSameScope(false).in(RequestScoped.class);

Proxy injected to bean with @Context behaves as expected for public method but executes package-private method as well.使用 @Context 注入到 bean 的代理对于公共方法的行为与预期的一样,但也执行包私有方法。 The problem is package-private method does not trigger MethodInterceptor so it actually does not reach the same instance get() does.问题是 package-private 方法不会触发 MethodInterceptor 所以它实际上没有达到 get() 所达到的相同实例。 The question is what is this "default" instance to which proxy forwards package-private method call.问题是代理将包私有方法调用转发到的这个“默认”实例是什么。 Calling get() method I reach different instance on different requests but calling store method ends up in the same instance every time so it behaves like singleton.调用 get() 方法时,我会根据不同的请求到达不同的实例,但调用 store 方法每次都会在同一个实例中结束,因此它的行为类似于单例。

There was one more thing I didn't mention - proxy behaving like singleton was injected into JacksonJsonProvider subclass.还有一件事我没有提到 - 代理行为像单例一样被注入到JacksonJsonProvider子类中。 So as far as I understand this subclass of JacksonJsonProvider is created only once in Jersey so instance of proxy injected into it does not change between requests.据我所知,JacksonJsonProvider 的这个子类在 Jersey 中仅创建一次,因此注入其中的代理实例不会在请求之间发生变化。

Proxy is basically an artificial subclass of MaskHolder with interceptor on public methods but it basically is MaskHolder with it's UUID field. Proxy 基本上是MaskHolder的人工子类,在公共方法上具有拦截器,但它基本上是MaskHolder及其 UUID 字段。 So if interceptor does not provide RequestScope bean we access "parent" MaskHolder.因此,如果拦截器不提供 RequestScope bean,我们将访问“父”MaskHolder。 And because the proxy instance is injected only once to JacksonJsonProvider it is the same across requests.而且因为代理实例只注入一次 JacksonJsonProvider 它在请求之间是相同的。

Injecting MaskHolder into resource results in different proxy instance (different UUID) across requests.MaskHolder注入资源会导致请求中出现不同的代理实例(不同的 UUID)。

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

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