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

我需要使用自定义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!

Inm小程序商店 | Vultr中文网

最佳答案

我从来没有实现过,所以我不知道所有的细微差别,但是简要地看一下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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值