需求:使用自定义注解,获得请求头中的字段,映射进入handler参数。
1、自定义注解
package com.example.demo.anno;
import java.lang.annotation.*;
/**
* @author shi
* @created 2019/11/28
*/
@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Info {
}
2、配置注解的解析器
package com.example.demo.anno;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
/**
* @author shi
* @created 2019/11/28
*/
public class InfoHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
//判定解析的注解,可以配置支持多个注解,这里只配置了一个
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
if(methodParameter.hasParameterAnnotation(Info.class))
return true;
return false;
}
//处理方法,如果有多个注解要区分开
//if(parameter.getParameterAnnotation(Info.class) != null)
//此处逻辑为获得请求header中的channel字段,映射generalRequest中的channel字段
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
String channel = request.getHeader("channel");
GeneralRequest generalRequest = new GeneralRequest();
generalRequest.setChannel(channel);
return generalRequest;
}
}
springmvc的配置
package com.example.demo.anno;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.util.List;
/**
* @author shi
* @created 2019/11/28
*/
@Configuration
public class InfoConfig extends WebMvcConfigurationSupport {
@Override
protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
super.addArgumentResolvers(argumentResolvers);
argumentResolvers.add(new InfoHandlerMethodArgumentResolver());
}
}
测试:
@RequestMapping("/testInfo")
public String testInfo(@Info GeneralRequest request){
logger.info("{}",request.getChannel());
return "success";
}