7

我有一个 Dropwizard 项目(使用 Jersey 2.x),我需要使用另一个依赖于 1.x 的 jersey-client 的库,我在让两者在类路径上共存时遇到了一些麻烦。看起来正在发生的事情是 HK2 正在从 javax.ws.rs.* 中找到任何实现提供程序的东西并尝试实例化它们。当它是 Jersey 1.x 中的一个类时,它需要的依赖注入不存在,我最终会遇到很多错误,例如:

Caused by: java.lang.IllegalArgumentException: The MultiPartConfig instance we expected is not present. Have you registered the MultiPartConfigProvider class?
  at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.<init>(MultiPartReaderClientSide.java:107)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
  at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
  at org.glassfish.hk2.utilities.reflection.ReflectionHelper.makeMe(ReflectionHelper.java:1107)
  at org.jvnet.hk2.internal.ClazzCreator.createMe(ClazzCreator.java:274)
  at org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:368)

有没有办法让 Jersey 2.x/HK2 忽略 com.sun.jersey.* 包空间中的任何内容?

4

1 回答 1

10

看起来 org.glassfish.jersey.internal.ServiceFinder 的默认行为是通过类路径上的 META-INF/services 查找服务实现。但是,它有一个 setIteratorProvider 方法,允许您设置备用 ServiceIteratorProvider 实现。我能够通过给它一个过滤掉来自 com.sun.jersey 的任何类名的实现来解决这个问题。*

public class Jersey2ServiceIteratorProvider extends ServiceFinder.ServiceIteratorProvider {

    ServiceFinder.DefaultServiceIteratorProvider delegate =  new ServiceFinder.DefaultServiceIteratorProvider();
    @Override
    public <T> Iterator<T> createIterator(Class<T> service, String serviceName,
                                          ClassLoader loader, boolean ignoreOnClassNotFound) {
        return delegate.createIterator(service, serviceName, loader, ignoreOnClassNotFound);
    }

    @Override
    public <T> Iterator<Class<T>> createClassIterator(Class<T> service, String serviceName,
                                                      ClassLoader loader, boolean ignoreOnClassNotFound) {
        final Iterator<Class<T>> delegateClassIterator = delegate.createClassIterator(service, serviceName, loader, ignoreOnClassNotFound);
        return Iterators.filter(delegateClassIterator, input -> !input.toString().startsWith("class com.sun.jersey"));
    }
}
于 2015-04-14T18:22:28.930 回答