目录
1.介绍SpringAop
组成:
(1)切面(Aspect)
定义 AOP 是针对某个统一的功能的,这个功能就叫做一个切面,比如用户登录功能或方法的统计日志,他们就各是一个切面。切面是由切点和通知组成的
(2)连接点(Join Point)
所有可能触发 AOP(拦截方法的点)就称为连接点
(3)切点(Pointcut)
切点的作用就是提供一组规则来匹配连接点,给满足规则的连接点添加通知,总的来说就是,定义 AOP 拦截的规则的
切点相当于保存了众多连接点的一个集合(如果把切点看成一个表,而连接点就是表中一条一条的数据)
(4)通知(Advice)
切面的工作就是通知
通知:规定了 AOP 执行的时机和执行的方法
2.模块前景
由于做的是安全产品管理系统,所以对产品的每个模块和操作都有明确的权限限制,采用SpringAop和自定义注解实现是我能想到的最简单的实现方式,
下面展示代码实现:
1.准备一个切面
这里的切点和其他依赖自行创建,核心就是当前用户权限和接口权限若不匹配就抛出异常,
抛出的异常也是自定义异常,代码在后面
import com.shenyan.domain.annotation.ApiLimitedRole;
import com.shenyan.domain.response.vo.LoginUserRespVo;
import com.shenyan.domain.response.vo.RoleInfoRespVo;
import com.shenyan.common.exception.ConditionException;
import com.shenyan.common.exception.ConditionExceptionEnum;
import com.shenyan.service.RoleInfoService;
import com.shenyan.service.UserInfoService;
import com.shenyan.common.support.UserSupport;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@Order(1)
@Component
@Aspect
public class ApiLimitedRoleAspect {
@Autowired
private UserSupport mUserSupport;
@Autowired
private UserInfoService userInfoService;
@Autowired
private RoleInfoService mRoleInfoService;
@Pointcut("@annotation(com.shenyan.domain.annotation.ApiLimitedRole)")
public void check(){