每个接口在被调用时,很可能需要调用该接口的用户信息,每次再去数据库查询该数据信息,势必会造成代码的大量重复,且还容易出错。
应用:把该次调用者用户的信息当做参数传到对应的方法。
比如:根据token获得到用户信息,将用户信息传到对应请求的method。
实现自定义参数解析器步骤:1、自定义注解 2、自定义参数解析器 3、注册
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Documented
public @interface UserToken {
}
@Component
public class TokenResolver implements HandlerMethodArgumentResolver {
@Autowired
private UserMapper userMapper;
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
if(methodParameter.hasParameterAnnotation(UserToken.class)){
return true;
}
return false;
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
String token = request.getHeader("token");
if(StringUtils.isEmpty(token)){
return null;
}
User user = userMapper.selectOneUser(Integer.parseInt(token));
return user;
}
}
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Autowired
private TokenResolver tokenResolver;
//@Override
//public void addInterceptors(InterceptorRegistry registry) {
//registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/user/*").excludePathPatterns("/user/getone2");
//}
@Override
public void addArgumentResolvers(List argumentResolvers) {
argumentResolvers.add(tokenResolver);
}
}
@RestController
public class UserController {
@GetMapping("/test/testHandlerMethodArgumentResolver")
public User testHandlerMethodArgumentResolver(@UserToken User user){
return user;
}
}