Spring boot 配置参数解析器

Spring boot 配置参数解析器

使用场景:将当前登录的用户注入到接口参数里。

例如:

    @RequestMapping(value = "/delete")
    @Transactional
    public ResultInfo deleteUserInfo(@User UserInfo userInfo) {

        return new ResultInfo(ErrCode.OK, "", userInfo.getUsername());
    }

首先创建User注解:

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

}

然后创建自定义解释器,当参数为UserInfo,且使用User注解标明的参数采用该解释器进行解释

@Component
public class UserInfoResolver implements HandlerMethodArgumentResolver {


    private UserInfoService userInfoService;

    public UserInfoResolver(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(UserInfo.class)
            && methodParameter.hasParameterAnnotation(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
        WebDataBinderFactory webDataBinderFactory) throws Exception {
        String username;
        try {
            username = (String) nativeWebRequest.getAttribute(Param.USERNAME, RequestAttributes.SCOPE_REQUEST);
        } catch (Exception e) {
            username = null;
        }

        if (username != null) {
            return userInfoService.findOneByUsername(username);
        }
        return new MissingServletRequestPartException(Param.USERNAME);
    }
}

将该解释器配置在项目中

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    private UserInfoService userInfoService;

    @Autowired
    public WebConfig(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Override
    protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new UserInfoResolver(userInfoService));
    }
}

此时deleteUserInfo(@User UserInfo userInfo)方法中的 userInfo就是当前用户的信息了。

猜你喜欢

转载自blog.csdn.net/wxpqqa/article/details/80543864