前言
本文素材的来源自业务部门技术负责人一次代码走查引发的故事,技术负责人在某次走查成员的代码时,发现他们的业务控制层大量充斥着如下的代码
@PostMapping("add")
public User add(@RequestBody User user, HttpServletRequest request){
String tenantId = request.getHeader("x-tenantid");
String appId = request.getHeader("x-appid");
user.setAppId(appId);
user.setTenantId(tenantId);
return user;
}
复制代码
他们的tenantId和appId是作为元数据放在请求头,而业务model又需要tenantId和appId,于是他们团队的成员就写出了形如上的代码,虽然这样的代码是能满足业务要求,但是大面积如上的写法,都是重复性的代码,很不优雅。后面这个技术负责人项通过自定义HandlerMethodArgumentResolver的方式来优雅解决这问题,他的代码形如下
@Data
public class MetaInfo {
private String tenantId;
private String appId;
}
复制代码
public class MetaInfoHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
private RequestResponseBodyMethodProcessor handlerMethodArgumentResolver;
public MetaInfoHandlerMethodArgumentResolver(RequestResponseBodyMethodProcessor handlerMethodArgumentResolver) {
this.handlerMethodArgumentResolver = handlerMethodArgumentResolver;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(RequestBody.class) && MetaInfo.class.isAssignableFrom(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
MetaInfo metaInfo = (MetaInfo) handlerMethodArgumentResolver.resolveArgument(parameter,mavContainer,webRequest,binderFactory);
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
metaInfo.setAppId(request.getHeader("x-appid"));
metaInfo.setTenantId(request.getHeader("x-tenantid"));
return metaInfo;
}
}
复制代码
@Configuration
public class WebConfig implements WebMvcConfi