6

我试图在它的 JSON 被解组后拦截一个资源调用。通过阅读一些论坛和帖子,我发现我可以通过实现org.glassfish.jersey.server.spi.internal.ResourceMethodInvocationHandlerProvider来做到这一点。这样做之后,我现在一直在尝试注册我的CustomResourceMethodInvocationHandler提供程序,以便 jersey/hk2 内部调用我重写的公共 InvocationHandler create(Invocable invocable)方法。任何帮助将非常感激!

4

1 回答 1

6

让我们看一下这种方法:

(使用Jersey 2.10JSON序列化测试)

===============

1) 实现一个自定义的 ResourceMethodInvocationHandlerProvider

package com.example.handler;

import java.lang.reflect.InvocationHandler;

import org.glassfish.jersey.server.model.Invocable;
import org.glassfish.jersey.server.spi.internal.ResourceMethodInvocationHandlerProvider;

public class CustomResourceInvocationHandlerProvider implements
        ResourceMethodInvocationHandlerProvider {

    @Override
    public InvocationHandler create(Invocable resourceMethod) {
            return new MyIncovationHandler();
    }

}

2) 实现一个自定义的 InvocationHandler

package com.example.handler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyIncovationHandler implements InvocationHandler {

    @Override
    public Object invoke(Object obj, Method method, Object[] args)
            throws Throwable {
        // optionally add some logic here
        Object result = method.invoke(obj, args);
        return result;
    }
}

3)创建一个自定义Binder类并注册你的CustomResourceInvocationHandlerProvider

package com.example.handler;

import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.spi.internal.ResourceMethodInvocationHandlerProvider;

public class CustomBinder extends AbstractBinder {

    @Override
    protected void configure() {
        // this is where the magic happens!
        bind(CustomResourceInvocationHandlerProvider.class).to(
                ResourceMethodInvocationHandlerProvider.class);
    }
}

4) 可选:在 ResourceMethodInvocationHandlerFactory 中设置断点

只是为了了解org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory中ResourceMethodInvocationHandlerProvider的选择是如何工作的。

===============

如您所见,最重要的是将您的CustomResourceInvocationHandlerProvider.class绑定到ResourceMethodInvocationHandlerProvider.class。完成此操作后,HK2 会知道您的 Provider 以及您的 Handler!

希望,我能帮上忙。

于 2014-09-24T07:58:50.130 回答