Jersey:如何使用自定义`ExceptionMapperFactory`

时间:2016-11-25 12:02:41

标签: java jersey jersey-2.0

我需要使用自定义ExceptionMapperFactory来实现自定义find()逻辑。

public class MyExceptionMapperFactory extends ExceptionMapperFactory {

    // [...]

    @Override
    public <T extends Throwable> ExceptionMapper<T> find(Class<T> type) {
         // [...]
    }
}

我如何使用/注册?

在我的RestApplication中注册它没有任何效果:

public class RestApplication extends ResourceConfig {

    public RestApplication() {
        register(JacksonFeature.class);
        register(JacksonXMLProvider.class);

        register(MyExceptionMapperFactory.class);
        register(SomeExceptionMapper.class, 600);
        register(OtherExceptionMapper.class, 550);

        // [...]
     }
}

有什么想法吗? TIA!

1 个答案:

答案 0 :(得分:3)

我从来没有实现过这一点,所以我不知道所有的细微差别,只是简单地看一下sourcetests,看起来你只需要hook it up to the DI system

register(new AbstractBinder() {
    @Override
    public void configure() {
        bindAsContract(MyExceptionMapperFactory.class)
                .to(ExceptionMappers.class)
                .in(Singleton.class);
    }
})

不确定如何禁用原始版本,但如果仍在使用,您可以尝试set a rank为您的工厂,以便在查找时,您的优先级

bindAsContract(MyExceptionMapperFactory.class)
        .to(ExceptionMappers.class)
        .ranked(Integer.MAX_VALUE)
        .in(Singleton.class);

更新

以下似乎会删除原始工厂,因为排名不起作用

@Provider
public class ExceptionMapperFactoryFeature implements Feature {

    @Override
    public boolean configure(FeatureContext context) {
        final ServiceLocator locator = ServiceLocatorProvider.getServiceLocator(context);
        final Descriptor<?> descriptor = locator.getBestDescriptor(new Filter() {
            @Override
            public boolean matches(Descriptor d) {
                return d.getImplementation().equals(ExceptionMapperFactory.class.getName());
            } 
        });
        ServiceLocatorUtilities.removeOneDescriptor(locator, descriptor);

        context.register(new AbstractBinder() {
            @Override
            public void configure() {
                bindAsContract(MyExceptionMapperFactory.class)
                        .to(ExceptionMappers.class)
                        .in(Singleton.class);
            }
        });
        return true;
    }
}