在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. jsp+mysql實(shí)現(xiàn)網(wǎng)頁(yè)的分頁(yè)查詢2. IntelliJ IDEA設(shè)置條件斷點(diǎn)的方法步驟3. Docker 部署 Prometheus的安裝詳細(xì)教程4. JavaScript Tab菜單實(shí)現(xiàn)過(guò)程解析5. ThinkPHP5 通過(guò)ajax插入圖片并實(shí)時(shí)顯示(完整代碼)6. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考7. js實(shí)現(xiàn)幻燈片輪播圖8. Ajax引擎 ajax請(qǐng)求步驟詳細(xì)代碼9. Android實(shí)現(xiàn)圖片自動(dòng)切換功能(實(shí)例代碼詳解)10. javascript設(shè)計(jì)模式 ? 建造者模式原理與應(yīng)用實(shí)例分析
