@RequestMapping("/strTest")
public Object strTest() {
return "jiang";
}
@RequestMapping("/test")
public Object test() {
return System.currentTimeMillis();
}
如上两个接口,返回string类型的接口在会报ClassCastException :Object cannot be cast to java.lang.String 的错误
@ControllerAdvice
public class ResultHandle implements ResponseBodyAdvice<Object> {
private static final Logger LOGGER = LoggerFactory.getLogger(ResultHandle.class);
@Override
public boolean supports(MethodParameter methodParameter,
Class<? extends HttpMessageConverter<?>> aClass) {
LOGGER.info("methodName = ", methodParameter.getMethod().getName());
return true;
}
@Nullable
@Override
public Object beforeBodyWrite(@Nullable Object o, MethodParameter methodParameter,
MediaType mediaType,
Class<? extends HttpMessageConverter<?>> aClass,
ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) {
String requestId = CommonUtils.getRequestId();
return ViewWrapResult.createSuccess(requestId, o);
}
}
谷歌搜索后搜到如下结果,https://stackoverflow.com/questions/44121648/controlleradvice-responsebodyadvice-failed-to-enclose-a-string-response
但是WebMvcConfigurerAdapter
已经被标注@Deprecated
,看注释更改为如下代码,亲测有效,我使用的是FastJson,但是仍然是使用MappingJackson2HttpMessageConverter
,亲测有效,但是不是非常清楚报错的原因,请大神指教
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(0, new MappingJackson2HttpMessageConverter());
}
}