在SpringBoot项目中使用自定义注解解决一些校验问题

首先,先上代码,方便讲解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PrivilegeAnnotation {
    boolean check() default false;
}
@Component
@Aspect
public class PrivilegeAspect {
    private static final LogUtil logger = LogUtil.getLogger(PrivilegeAspect.class, "erp-report-service");
    @Autowired
    private RedisTemplate redisTemplate;
    @Before("execution(public * com.didichuxing.erp.report.api.controller.hr.*.*(..)) && @annotation(com.didichuxing.erp.report.basic.aop.annotations.PrivilegeAnnotation)")
    public void checkPrivilege(JoinPoint joinPoint){

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        PrivilegeAnnotation privilegeAnnotation = signature.getMethod().getAnnotation(PrivilegeAnnotation.class);
        if (Objects.isNull(privilegeAnnotation)) {
            return;
        }
        if (privilegeAnnotation.check()){
            String ldap = UserUtil.getUser().getLdap();
            logger.info("PrivilegeAspect.checkPrivilege", " ldap:{}", ldap);
            if (Objects.nonNull(ldap)){
                boolean hasAuthorized = false;
                // 从缓存中获取管理员的所有数据
                List users = redisTemplate.opsForList().range(HR_BOARD_ADMIN_USER_KEY, 0, -1);
                logger.info("PrivilegeAspect.checkPrivilege", " users:{}", users);
                if (!CollectionUtils.isEmpty(users)){
                    List ldaps = users.stream().map(User::getDisplayName).collect(Collectors.toList());
                    if (ldaps.contains(ldap)){
                        hasAuthorized = true;
                    }

                }

                if (!hasAuthorized){
                    throw new BasicException(MessageCode.NO_PRIVILEGE_DO.getCode(),MessageCode.NO_PRIVILEGE_DO.getMessage());
                }
            }
        }
    }
}

通常自定义注解是和定义的切面同事存在的,因为我们通过自定义切面来决定切点是否执行增强的方法.

你可能感兴趣的:(在SpringBoot项目中使用自定义注解解决一些校验问题)