在springboot中使用注解将值注入参数的操作

后端的许多管理系统需要登陆者的信息,如shiro登陆后,会将登陆者的信息存储在shiro的session,在使用时需要多行代码获取用户信息。可以把获取在shiro中的登陆者信息封装在一个类中,使用时获取。本文主要讲述如何使用注解将值注入参数,shiro的配置请自行百度。

定义注解

新建一个InfoAnnotation.java的注解类,用于注解参数,代码如下:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface InfoAnnotation {
 String value() default "userId";//默认获取userId的值
}

定义注解处理类

新建一个InfoResolver类,AOP无法将值注入参数,需要继承HandlerMethodArgumentResolver类,代码如下:

public class InfoResolver implements HandlerMethodArgumentResolver {
 //使用自定义的注解
 @Override
 public boolean supportsParameter(MethodParameter methodParameter) {
 return methodParameter.hasParameterAnnotation(InfoAnnotation.class);
 }

 //将值注入参数
 @Override
 public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
 //获取捕获到的注解
 InfoAnnotation annotation = methodParameter.getParameterAnnotation(InfoAnnotation.class);
 String value = annotation.value();
 //获取需要注入值得逻辑
 //该例子在shiro中获取userId或者用户信息
 if (value == null || "".equalsIgnoreCase(value) || value.equalsIgnoreCase("userId")){
  User user = (User)SecurityUtils.getSubject().getSession().getAttribute("user");
  if (user == null){
  return 1;
  }
  return user.getId();
 } else if ("user".equalsIgnoreCase(value)){
  return SecurityUtils.getSubject().getSession().getAttribute("user");
 }
 return value;
 }
}

使springboot支持该拦截器

修改启动类,继承WebMvcConfigurationSupport类,添加自定义得拦截器,代码如下:

@SpringBootApplication
public class DemoApplication extends WebMvcConfigurationSupport {
 public static void main(String[] args) {
 SpringApplication.run(DemoApplication.class, args);
 }
 //添加自定义的拦截器
 @Override
 public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers){
 super.addArgumentResolvers(argumentResolvers);
 argumentResolvers.add(new InfoResolver());
 }
}

测试

测试用例,如下代码

@GetMapping
public BaseResponse<?> test(@InfoAnnotation int userId){
 return ResponseUtil.successResponse(userId);
}

登陆返回的信息

调用测试用例返回的信息

可以看到登陆返回的用户信息的id和测试用例返回的data一致。

以上这篇在springboot中使用注解将值注入参数的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。