通过自定义 @CurrentUser 获取当前登录用户

1、定义 @CurrenUser注解

package com.presoft.wydl.common.config;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.ElementType;
@Target(ElementType.PARAMETER)          // 可用在方法的参数上
@Retention(RetentionPolicy.RUNTIME)     // 运行时有效
public @interface CurrentUser {
	
}

2、添加参数解析器 

要想 @CurrentUser 起作用,需要编写一个配套解析器,做法是实现 spring 提供的 HandlerMethodArgumentResolver 接口。

package com.presoft.wydl.common.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import com.presoft.wydl.packs.system.model.UserInfo;


@Configuration
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

	@Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(UserInfo.class)
                && parameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //取出第二节中放入请求中的用户信息
    	UserInfo user = (UserInfo)webRequest.getAttribute("currentUser", RequestAttributes.SCOPE_REQUEST);
        if (user != null) {
            return user;
        }
        throw new MissingServletRequestPartException("currentUser");
    }

}

3、配置参数解析器

在 WebMvcConfigurer.java 中 Override addArgumentResolvers 方法

//@Configuration
public class InterceptorConfig extends   WebMvcConfigurationSupport {
	
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(new CurrentUserMethodArgumentResolver());
    }
}

4、实例

@ApiOperation("获取企业信息")
	@RequestMapping(value = "/list",method = RequestMethod.POST)
	public Response list(EnterpriseVo vo,@CurrentUser UserInfo user) {
		return enterpriseService.selectByParams(vo);
	}

5、 文件目录 

原文 https://www.jianshu.com/p/01a6a61d9e02

Logo

前往低代码交流专区

更多推荐