mitao
2025-02-21 31573d6180d15ef65ed0df9c2732495f40b12663
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.panzhihua.service_equipment.resolvers;
 
import com.panzhihua.common.model.dtos.equipment.UnionUserDto;
import com.panzhihua.common.utlis.Constant;
import com.panzhihua.service_equipment.annotation.CurrentUser;
import com.panzhihua.service_equipment.service.UnionUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
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.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
 
/**
 * 增加方法注入,将含有CurrentUser注解的方法参数注入当前登录用户
 */
@Component
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
 
    @Lazy
    @Autowired
    private UnionUserService userService;
 
//    ComEquipmentUnionUserFeign feignUserService = ComEquipmentUnionUserFeign.getBean(ComEquipmentUnionUserFeign.class);
 
 
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果参数类型是User并且有CurrentUser注解则支持
        if (parameter.getParameterType().isAssignableFrom(UnionUserDto.class) &&
                parameter.hasParameterAnnotation(CurrentUser.class)) {
            return true;
        }
        return false;
    }
 
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //取出鉴权时存入的登录用户Id
        Long currentUserId = (Long) webRequest.getAttribute(Constant.CURRENT_USER_ID, RequestAttributes.SCOPE_REQUEST);
        if (currentUserId != null) {
            //从数据库中查询并返回
            UnionUserDto sysUser=userService.selectById(currentUserId);
            if(sysUser!=null)
            {
                return sysUser;
            }
 
        }
        return null;
//        throw new MissingServletRequestPartException(Constant.CURRENT_USER_ID);
    }
}