Spring MVC: Appropriate extension point for wrapping API Responses

前端 未结 1 716
逝去的感伤
逝去的感伤 2021-02-06 02:56

I have a simple REST API, build using Spring MVC @Controllers and @RequestMapping. I\'d like to start wrapping responses to provide additional with met

相关标签:
1条回答
  • 2021-02-06 03:41

    Here's the implementation I used:

    public class MetadataInjectingReturnValueHandler implements HandlerMethodReturnValueHandler {
    
        private final HandlerMethodReturnValueHandler delegate;
    
        public MetadataInjectingReturnValueHandler(HandlerMethodReturnValueHandler delegate)
        {
            this.delegate = delegate;
        }
        @Override
        public boolean supportsReturnType(MethodParameter returnType) {
            return delegate.supportsReturnType(returnType);
        }
    
        @Override
        public void handleReturnValue(Object returnValue,
                MethodParameter returnType, ModelAndViewContainer mavContainer,
                NativeWebRequest webRequest) throws Exception {
            returnValue = wrapResult(returnValue); //Omitted
            delegate.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
        }
    }
    
    
    
    @Component
    public class MetadataInjectionFactoryBean implements InitializingBean {
    
        @Autowired
        private RequestMappingHandlerAdapter adapter;
        @Override
        public void afterPropertiesSet() throws Exception {
            HandlerMethodReturnValueHandlerComposite returnValueHandlers = adapter.getReturnValueHandlers();
            List<HandlerMethodReturnValueHandler> handlers = Lists.newArrayList(returnValueHandlers.getHandlers());
            decorateHandlers(handlers);
            adapter.setReturnValueHandlers(handlers);
        }
        private void decorateHandlers(List<HandlerMethodReturnValueHandler> handlers) {
            for (HandlerMethodReturnValueHandler handler : handlers) {
                if (handler instanceof RequestResponseBodyMethodProcessor)
                {
                    MetadataInjectingReturnValueHandler decorator = new MetadataInjectingReturnValueHandler(handler);
                    int index = handlers.indexOf(handler);
                    handlers.set(index, decorator);
                    log.info("Metadata Injecting decorator wired up");
                    break;
                }
            }       
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题