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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

一条独立特行的咸鱼   2021-04-22 我要评论

后端的许多管理系统需要登陆者的信息,如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中使用注解将值注入参数的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们