在springboot中使用注解將值注入?yún)?shù)的操作
后端的許多管理系統(tǒng)需要登陸者的信息,如shiro登陸后,會(huì)將登陸者的信息存儲(chǔ)在shiro的session,在使用時(shí)需要多行代碼獲取用戶信息。可以把獲取在shiro中的登陸者信息封裝在一個(gè)類中,使用時(shí)獲取。本文主要講述如何使用注解將值注入?yún)?shù),shiro的配置請(qǐng)自行百度。
定義注解
新建一個(gè)InfoAnnotation.java的注解類,用于注解參數(shù),代碼如下:
@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME)public @interface InfoAnnotation { String value() default 'userId';//默認(rèn)獲取userId的值}
定義注解處理類
新建一個(gè)InfoResolver類,AOP無法將值注入?yún)?shù),需要繼承HandlerMethodArgumentResolver類,代碼如下:
public class InfoResolver implements HandlerMethodArgumentResolver { //使用自定義的注解 @Override public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.hasParameterAnnotation(InfoAnnotation.class); } //將值注入?yún)?shù) @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支持該攔截器
修改啟動(dòng)類,繼承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()); }}
測(cè)試
測(cè)試用例,如下代碼
@GetMappingpublic BaseResponse<?> test(@InfoAnnotation int userId){ return ResponseUtil.successResponse(userId);}
登陸返回的信息
調(diào)用測(cè)試用例返回的信息
可以看到登陸返回的用戶信息的id和測(cè)試用例返回的data一致。
以上這篇在springboot中使用注解將值注入?yún)?shù)的操作就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python中scrapy處理項(xiàng)目數(shù)據(jù)的實(shí)例分析2. Hybris在idea中debug配置方法詳解3. 在idea中為注釋標(biāo)記作者日期操作4. jsp cookie+session實(shí)現(xiàn)簡(jiǎn)易自動(dòng)登錄5. XPath入門 - XSL教程 - 36. .NET Core Web APi類庫(kù)內(nèi)嵌運(yùn)行的方法7. .NET6使用ImageSharp實(shí)現(xiàn)給圖片添加水印8. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車9. ASP.NET MVC使用Boostrap實(shí)現(xiàn)產(chǎn)品展示、查詢、排序、分頁(yè)10. .net如何優(yōu)雅的使用EFCore實(shí)例詳解
