美文网首页
@ControllerAdvice 接收String时 cann

@ControllerAdvice 接收String时 cann

作者: 姜小鱼Qyer | 来源:发表于2018-09-30 12:01 被阅读0次
     @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());
      }
    }
    

    相关文章

      网友评论

          本文标题:@ControllerAdvice 接收String时 cann

          本文链接:https://www.haomeiwen.com/subject/tgqwoftx.html