午夜剧场伦理_日本一道高清_国产又黄又硬_91黄色网战_女同久久另类69精品国产_妹妹的朋友在线

您的位置:首頁技術文章
文章詳情頁

在springboot中使用注解將值注入參數的操作

瀏覽:178日期:2023-05-21 13:47:41

后端的許多管理系統需要登陸者的信息,如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類,添加自定義得攔截器,代碼如下:

@SpringBootApplicationpublic 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()); }}

測試

測試用例,如下代碼

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

登陸返回的信息

在springboot中使用注解將值注入參數的操作

調用測試用例返回的信息

在springboot中使用注解將值注入參數的操作

可以看到登陸返回的用戶信息的id和測試用例返回的data一致。

以上這篇在springboot中使用注解將值注入參數的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
主站蜘蛛池模板: 亚洲天堂一区在线观看 | 成人免费av在线 | 天堂在线一区二区 | 精品国产乱码久久久久久久 | 欧美综合在线观看 | 亚洲午夜18毛片在线看 | 久久久久久久久国产 | 五月激情综合 | 99热视 | 久久免费精品视频 | 日韩成人一区 | 综合天堂 | 久久xxx| 久久福利网站 | 懂色av一区二区三区 | 爱爱高潮视频 | 丁香色婷婷 | 日韩免费精品 | 手机看片日韩欧美 | 高h文视频 | 91欧美日韩 | 日本精品免费 | 波多野结衣久久 | 免费手机av | a级黄色片免费看 | 九九热精品视频 | 91久久精品国产91久久 | 真实的国产乱xxxx在线91 | 欧美人成在线 | 四虎激情 | 久久精品久久久久久久 | 欧美视频一二三 | 一区精品在线观看 | 国产精品久久久久久久天堂第1集 | 一级片日韩 | 九九av | 成人在线视频免费观看 | 亚洲一区二区三区在线免费观看 | 欧美精品99久久久 | 日韩两性视频 | 日韩女优在线播放 |