瀏覽代碼

添加通过注解获取登录用户信息 -- 使用方法--myFun(@LoginAppUser TbAppUser user)

luobo 4 年之前
父節點
當前提交
6cfe964d33

+ 25 - 0
ruoyi-app/src/main/java/com/ruoyi/app/annotation/LoginAppUser.java

@@ -0,0 +1,25 @@
+/**
+ * Copyright (c) 2016-2019 人人开源 All rights reserved.
+ *
+ * https://www.renren.io
+ *
+ * 版权所有,侵权必究!
+ */
+
+package com.ruoyi.app.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * 登录用户信息
+ *
+ * @author Mark sunlightcs@gmail.com
+ */
+@Target(ElementType.PARAMETER)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface LoginAppUser {
+
+}

+ 44 - 0
ruoyi-app/src/main/java/com/ruoyi/app/resolver/LoginAppUserHandlerMethodArgumentResolver.java

@@ -0,0 +1,44 @@
+/**
+ * Copyright (c) 2016-2019 人人开源 All rights reserved.
+ *
+ * https://www.renren.io
+ *
+ * 版权所有,侵权必究!
+ */
+
+package com.ruoyi.app.resolver;
+
+import com.ruoyi.app.annotation.LoginAppUser;
+import com.ruoyi.app.base.AppTokenService;
+import com.ruoyi.app.domain.TbAppUser;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.MethodParameter;
+import org.springframework.stereotype.Component;
+import org.springframework.web.bind.support.WebDataBinderFactory;
+import org.springframework.web.context.request.NativeWebRequest;
+import org.springframework.web.method.support.HandlerMethodArgumentResolver;
+import org.springframework.web.method.support.ModelAndViewContainer;
+
+/**
+ * 有@LoginAppUser注解的方法参数,注入当前登录用户
+ *
+ * @author luobo
+ */
+@Component
+public class LoginAppUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
+    @Autowired
+    private AppTokenService appTokenService;
+
+    @Override
+    public boolean supportsParameter(MethodParameter parameter) {
+        //接收数据类型及注解类型
+        return parameter.getParameterType().isAssignableFrom(TbAppUser.class) && parameter.hasParameterAnnotation(LoginAppUser.class);
+    }
+
+    @Override
+    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
+                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
+        //直接从AppTokenService里获取登录用户信息
+        return appTokenService.getLoginUser().getUser();
+    }
+}