栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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 argumentResolvers){
 super.addArgumentResolvers(argumentResolvers);
 argumentResolvers.add(new InfoResolver());
 }
}

测试

测试用例,如下代码

@GetMapping
public baseResponse test(@InfoAnnotation int userId){
 return ResponseUtil.successResponse(userId);
}

登陆返回的信息

调用测试用例返回的信息

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/134311.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号