像@Ralph建議你可以使用HandlerMethodReturnValueHandler來包裝你的處理程式傳回值.
實作這一目标的最簡單方法是擴充RequestResponseBodyMethodProcessor并稍微改變它的行為.最好的方法是建立一個自定義注釋來标記處理程式方法.這将確定預設情況下将調用HandlerMethodReturnValueHandler而不是RequestMappingHandlerAdapter包含的其他HandlerMethodReturnValueHandler.
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ResultResponseBody {}
下面是名為ResultResponseHandlerMethodProcessor的自定義HandlerMethodReturnValueHandler的簡單實作,它将支援從使用ResultResponseBody注釋的方法傳回的值.這很簡單.隻需覆寫supportsReturnType()和handleReturnValue()方法以滿足您的需要(将傳回值包裝到Result類型中).
public class ResultResponseHandlerMethodProcessor extends RequestResponseBodyMethodProcessor {
public ResultResponseHandlerMethodProcessor(final List> messageConverters) {
super(messageConverters);
}
public ResultResponseHandlerMethodProcessor(final List> messageConverters,final ContentNegotiationManager contentNegotiationManager) {
super(messageConverters,contentNegotiationManager);
}
@Override
public boolean supportsReturnType(final MethodParameter returnType) {
return returnType.getMethodAnnotation(ResultResponseBody.class) != null;
}
@Override
public void handleReturnValue(final Object returnValue,final MethodParameter returnType,final ModelAndViewContainer mavContainer,final NativeWebRequest webRequest) throws IOException,HttpMediaTypeNotAcceptableException {
super.handleReturnValue(Result.ok(returnValue),returnType,mavContainer,webRequest);
}
}
剩下的唯一事情是将此類添加到自定義HandlerMethodReturnValueHandlers清單中,并為其提供MappingJackson2HttpMessageConverter執行個體.
@EnableWebMvc
@Configuration
public class ApplicationConfiguration extends WebMvcConfigurerAdapter
@Override
public void addReturnValueHandlers(final List returnValueHandlers) {
List> messageConverters = new ArrayList<>();
messageConverters.add(new MappingJackson2HttpMessageConverter());
returnValueHandlers.add(new ResultResponseHandlerMethodProcessor(messageConverters));
}
}