Uploaded image for project: 'Spring Framework'
  1. Spring Framework
  2. SPR-17539

ResponseBodyAdvice should ignore non-match type instead throw exception

    Details

    • Type: Improvement
    • Status: Resolved
    • Priority: Minor
    • Resolution: Works as Designed
    • Affects Version/s: 5.0.9
    • Fix Version/s: None
    • Component/s: Web
    • Labels:
      None
    • Last commented by a User:
      true

      Description

      When I use 

      public class MyAdvice implements ResponseBodyAdvice<MyVo>

      and my response data is

      ResponseEntity<AnotherVo>

      ResponseBodyAdvice will throw ClassCastException, because we can't use "supports" to check the type. It make type declare in ResponseBodyAdvice interface useless.

       

      Currently, there is a workaround, use Object

      ResponseBodyAdvice<Object>
      

      and check the type in beforeBodyWrite, like this

      @Override
      public Object beforeBodyWrite(Object o, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
          if (!(o instanceof MyVo)) {
              return o;
          }
          // do rest things here
      }
      

      but it doesn't look like a best practice.

       

      update:

      after study the source, I found there is a class cast before call beforeBodyWrite

      RequestResponseBodyAdviceChain

      private <T> Object processBody(@Nullable Object body, MethodParameter returnType, MediaType contentType,
            Class<? extends HttpMessageConverter<?>> converterType,
            ServerHttpRequest request, ServerHttpResponse response) {
      
         for (ResponseBodyAdvice<?> advice : getMatchingAdvice(returnType, ResponseBodyAdvice.class)) {
            if (advice.supports(returnType, converterType)) {
               body = ((ResponseBodyAdvice<T>) advice).beforeBodyWrite((T) body, returnType,
                     contentType, converterType, request, response);
            }
         }
         return body;
      }
      

      Can we check body is T before call beforeBodyWrite?

        Attachments

          Activity

            People

            • Assignee:
              rstoya05-aop Rossen Stoyanchev
              Reporter:
              abccbaandy abccbaandy
              Last updater:
              Spring Issuemaster
            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved:
                Days since last comment:
                47 weeks, 2 days ago