在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無(wú)法將值注入?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. 詳解CSS偽元素的妙用單標(biāo)簽之美2. XML入門的常見(jiàn)問(wèn)題(四)3. ASP基礎(chǔ)知識(shí)VBScript基本元素講解4. 利用CSS3新特性創(chuàng)建透明邊框三角5. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼6. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁(yè)的方法7. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式8. HTML5 Canvas繪制圖形從入門到精通9. XHTML 1.0:標(biāo)記新的開(kāi)端10. JSP的Cookie在登錄中的使用
