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

 2023-09-19 阅读 24 评论 0

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

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

}

登陆返回的信息

a7fb659bcb9eaea217a25457a7706a2c.png

调用测试用例返回的信息

5af4811b68b186925260d2b41ea90dc1.png

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

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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/77695.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息