欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2020-12-27 16:28:53|栏目:JAVA代码|点击:

后端的许多管理系统需要登陆者的信息,如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一致。

上一篇:Java异常处理实例分析

栏    目:JAVA代码

下一篇:图书管理系统java版

本文标题:在springboot中使用注解将值注入参数的操作

本文地址:http://www.codeinn.net/misctech/37136.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有