spring项目实战(二):若依框架实现实现权限校验的AOP实例

1、编写DataFilter注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataFilter {

    /**
     * 部门表的别名
     */
    public String deptAlias() default "";

    /**
     * 用户表的别名
     */
    public String userAlias() default "";

}
  • @Target(ElementType.METHOD)注解作用域,作用在方法上

  • @Retention(RetentionPolicy.RUNTIME)用于定义注解的生命周期

    • SOURCE:在源文件中有效(即源文件保留)
    • CLASS:在class文件中有效(即class保留)
    • RUNTIME:在运行时有效(即运行时保留)
2、编写切面类
@Aspect
@Component
@Slf4j
public class DataFilterAspect {   
    
    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_FILTER = "dataFilter";

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, DataFilter controllerDataScope) throws Throwable {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }

    protected void handleDataScope(final JoinPoint joinPoint, DataFilter controllerDataFilter) {
        ...
    }

    // 拼接权限sql前先清空params.dataScope参数防止注入
    private void clearDataScope(final JoinPoint joinPoint) {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(DATA_SCOPE, "");
        }
    }
}
  • @Aspect 用于表示该类为切面类
  • controllerDataScope:切面方法是通过 @annotation(controllerDataScope) 切入点表达式来匹配那些被 DataFilter 注解标记的方法
  • 切入点注解
    • @Before:切面切入目标方法之前执行
    • @After:目标方法执行之后执行,它通常用于执行一些清理或日志记录操作
    • @Around:切面方法中调用ProceedingJoinPointproceed方法,即调用目标方法,最灵活的方式,可以用于性能监测、事务管理等复杂场景
    • @AfterReturning
    • @AfterThrowing
  • 是否return
    • 需要return:如果在切面方法中使用 joinPoint.proceed() 来调用目标方法,并获取返回值,然后根据需要对返回值进行修改或处理
    • 不需要return:不打算修改返回值,可以不包含 return 语句
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值