在Jersey中注册自定义ResourceMethodInvocationHandler

jmd*_*dev 4 jersey hk2

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

小智 5

我们来看看这种方法:

(使用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();
    }

}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

只是为了了解的选择如何ResourceMethodInvocationHandlerProviderorg.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory工作.

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

如您所见,最重要的是将CustomResourceInvocationHandlerProvider.class绑定到ResourceMethodInvocationHandlerProvider.class.完成此操作后,HK2了解您的提供商以及您的处理程序!

希望,我能提供帮助.