Jackson JsonParseExceptionMapper 和 JsonMappingExceptionMapper 阴影自定义映射器
我的项目使用 Spring Boot + Jersey 2.
My project uses Spring Boot + Jersey 2.
我为 JsonParseException 创建了自定义 Jackson 映射器,但它没有被调用,而是使用了标准 Jackson JsonParseExceptionMapper.
I created custom Jackson mapper for JsonParseException, but it didn't get called, standard Jackson JsonParseExceptionMapper used instead.
我的自定义映射器:
package com.rmn.gfc.common.providers;
import ...
@Provider
public class JsonParseExceptionHandler implements ExceptionMapper<JsonParseException> {
@Override
public Response toResponse(JsonParseException exception) {
return Response
.status(Response.Status.BAD_REQUEST)
// entity ...
.build();
}
}
我这样注册我的映射器:
I register my mapper like this:
@Component
public class OrderServiceResourceConfig extends ResourceConfig {
public OrderServiceResourceConfig() {
packages("com.rmn.gfc.common.providers");
}
}
我确信映射器注册没问题,因为该包中的其他自定义映射器正在工作,但 JsonParseException 的一个映射器被 Jersey 标准 JsonParseExceptionMapper 遮蔽.
I am sure that mapper registration is fine because other custom mappers from this package is working, but one for JsonParseException is shadowed by Jersey standard JsonParseExceptionMapper.
如何用我的实现覆盖标准的 Jackson JsonParseExceptionMapper?
How could I override standard Jackson JsonParseExceptionMapper with my implementation?
推荐答案
我找到了适合我的解决方案.
在自定义映射器上使用 javax.annotation.Priority
使其覆盖 Jackson 默认映射器,例如:
I found solution that is fine for me.
Use javax.annotation.Priority
on your custom mapper to make it override Jackson default mapper, e.g.:
@Provider
@Priority(1)
public class JsonParseExceptionHandler implements ExceptionMapper<JsonParseException> {
// ...
}
或者,如果你通过 ResourceConfig 注册 JAX-RS 组件,你可以像这样指定优先级:
OR , if you register JAX-RS components via ResourceConfig, you can specify priority like this:
public class MyResourceConfig extends ResourceConfig {
public MyResourceConfig() {
register(JsonMappingExceptionHandler.class, 1);
register(JsonParseExceptionHandler.class, 1);
// ...
}
}
数字越小优先级越高.javax.ws.rs.Priorities
有一些预定义的优先级常量.
The lower number the highest priority.
javax.ws.rs.Priorities
has some predefined constants for priorities.
相关文章