@RequestBody正是依賴HandlerMethodArgumentResolver來生效的榕栏,我們也可以定義一些自定義的注解,來優(yōu)化我們的項目蕾各。
注解 | 解析器類 |
---|---|
@RequestParam | RequestParamMethodArgumentResolver |
@PathVariable | PathVariableMethodArgumentResolver |
@RequestBody | RequestResponseBodyMethodProcessor |
@CookieValue | ServletCookieValueMethodArgumentResolver |
使用場景
例如以下這個例子扒磁,我們從Header中取得token數(shù)據(jù),然后將token信息轉(zhuǎn)化為用戶信息式曲。但是這一步操作可以在HandlerMethodArgumentResolver
來執(zhí)行妨托,在Controller的參數(shù)中獲取到的就是用戶信息。
1.1 自定義注解
/**
* 放在參數(shù)數(shù)吝羞,解析header里面的token讀取為參數(shù)對象
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestToken {
}
1.2 解析器
/**
* 參數(shù)解析器
*/
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
private TokenService tokenService;
public UserInfoArgumentResolver(TokenService tokenService) {
this.tokenService = tokenService;
}
/**
* 是否校驗參數(shù)兰伤,
* 1. 參數(shù)上有RequestToken注解;
* 2. 參數(shù)對象為{@link UserInfo};
* 若滿足以上條件钧排,則處理
* {@link UserInfoArgumentResolver#resolveArgument(MethodParameter, ModelAndViewContainer, NativeWebRequest, WebDataBinderFactory)}方法
*/
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(RequestToken.class) != null
&& UserInfo.class.isAssignableFrom(parameter.getParameterType());
}
/**
* 對參數(shù)的處理
* 1. 讀取header里面的參數(shù)敦腔,去service中完成組裝,然后返回出去
*/
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest nativeRequest = (HttpServletRequest) webRequest.getNativeRequest();
//在header里面獲取參數(shù)
String token = nativeRequest.getHeader("token");
//去service中獲取參數(shù)
return tokenService.getUserInfoByToken(token);
}
}
1.3 放入Spring容器中
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Autowired
private TokenService tokenService;
/**
* 設(shè)置參數(shù)轉(zhuǎn)換器
*/
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new UserInfoArgumentResolver(tokenService));
}
}
1.4 測試方法
@Slf4j
@RestController
public class SAOController {
@RequestMapping(value = "/sao/userInfo")
public String userInfo(@RequestToken UserInfo userInfo) {
return JSON.toJSONString(userInfo);
}
}