问题
I need to use a custom ExceptionMapperFactory
to implement a custom find()
logic.
public class MyExceptionMapperFactory extends ExceptionMapperFactory {
// [...]
@Override
public <T extends Throwable> ExceptionMapper<T> find(Class<T> type) {
// [...]
}
}
How can I use/register it?
Registering it in my RestApplication has no effect:
public class RestApplication extends ResourceConfig {
public RestApplication() {
register(JacksonFeature.class);
register(JacksonXMLProvider.class);
register(MyExceptionMapperFactory.class);
register(SomeExceptionMapper.class, 600);
register(OtherExceptionMapper.class, 550);
// [...]
}
}
Any ideas? TIA!
回答1:
I've never implemented this, so I don't know all the nuances, but briefly looking at the source and the tests, it looks like you just need to hook it up to the DI system
register(new AbstractBinder() {
@Override
public void configure() {
bindAsContract(MyExceptionMapperFactory.class)
.to(ExceptionMappers.class)
.in(Singleton.class);
}
})
Not sure how to disable the original one, but if it is still being used, you can try to set a rank for your factory so that when it's looked up, yours will take precedence
bindAsContract(MyExceptionMapperFactory.class)
.to(ExceptionMappers.class)
.ranked(Integer.MAX_VALUE)
.in(Singleton.class);
UPDATE
It seems the following will remove the original factory, since the ranking doesn't work
@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;
}
}
来源:https://stackoverflow.com/questions/40804651/jersey-how-to-use-a-custom-exceptionmapperfactory