在springboot中使用注解將值注入參數的操作
后端的許多管理系統需要登陸者的信息,如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);}
登陸返回的信息
調用測試用例返回的信息
可以看到登陸返回的用戶信息的id和測試用例返回的data一致。
以上這篇在springboot中使用注解將值注入參數的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: