路径参数绑定至bean

路径参数过多时,频繁的写@PathVariable太过繁琐,如下

自定义HandlerMethodArgumentResolver,在解析完body时,将路径参数进行解析,然后放入请求头对象中。注:以下方法仅限于post请求,且路径参数绑定至body对象中

自定义任意注解,标识该对象需要将路径参数放入,如下:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SelfPathVariable {
}

接口定义如下 

@PostMapping("/{channel}/productquery/{version}/{timestamp}/{sign}")
public QueryProductResponse estimatedPrice(@SelfPathVariable @RequestBody QueryProductRequest request) {
    return new QueryProductResponse();
}

 自定义的HandlerMethodArgumentResolver

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.lang.reflect.Field;
import java.util.Map;

import static org.springframework.web.servlet.HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;


public class SelfRequestResponseBodyMethodProcessor implements HandlerMethodArgumentResolver {

    private RequestResponseBodyMethodProcessor processor;

    public CtripRequestResponseBodyMethodProcessor(RequestResponseBodyMethodProcessor processor) {
        this.processor = processor;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(SelfPathVariable.class) && processor.supportsParameter(parameter);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Object o = processor.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
        if (o instanceof AbstractSelfRequest) {
            Map<String, String> attribute = (Map<String, String>) webRequest.getAttribute(URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
            if (attribute != null && attribute.size() > 0) {
                for (Map.Entry<String, String> entry : attribute.entrySet()) {
                    Field field = findField(o.getClass(), entry.getKey());
                    if (field != null) {
                        field.setAccessible(true);
                        field.set(o, entry.getValue());
                    }
                }
            }
        }
        return o;
    }

    private Field findField(Class<?> aClass, String fieldName) throws NoSuchFieldException {
        Field field;
        return aClass.getSuperclass() != Object.class ? (field = findField(aClass.getSuperclass(), fieldName)) != null ? field : aClass.getDeclaredField(fieldName) : null;
    }

}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @PostConstruct
    public void init() {
        List<HandlerMethodArgumentResolver> resolvers = requestMappingHandlerAdapter.getArgumentResolvers();
        if (resolvers != null) {
            List<HandlerMethodArgumentResolver> newHandlers = new ArrayList<>(resolvers.size() + 1);
            for (HandlerMethodArgumentResolver resolver : resolvers) {
                if (resolver instanceof RequestResponseBodyMethodProcessor) {
                    newHandlers.add(new SelfRequestResponseBodyMethodProcessor((RequestResponseBodyMethodProcessor) resolver));
                }
                newHandlers.add(resolver);
            }
            requestMappingHandlerAdapter.setArgumentResolvers(newHandlers);
        }
    }

}

以上注入自定义的HandlerMethodArgumentResolver的方式太过笨拙,自行优化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值