SpringBoot自定义注解+切面横向处理业务

业务需求:对接口增加权限验证功能


首先引入jar包

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>

自定义注解

import java.lang.annotation.*;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface VerifyAuthority {

    VerifyAuthorityElement value() default VerifyAuthorityElement.DGRB;

}



//配置枚举元素
public enum VerifyAuthorityElement {


    DGRB;

   //后续继续添加

}

看些接口如何配置:

@RestController
@RequestMapping("dgrb")
@Slf4j
public class SendMessageController {



    @PostMapping("sendMessage")
    @VerifyAuthority(value = VerifyAuthorityElement.DGRB)
    public Result sendMessage(@RequestBody Map<String, Object> paramMap) {
      //接口处理逻辑
    }

}

切面如何写呢


import com.xx.dgrb.dao.SystemSettingsDao;
import com.xx.dgrb.model.Result;
import com.xx.dgrb.model.SystemSettings;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
@Slf4j
@Aspect
public class VerifyAuthorityHandler {

    @Autowired
    private SystemSettingsDao systemSettingsDao;

    @Autowired
    private DgrbHandler dgrbHandler;

    //指定这个注解,做切面
    @Pointcut("@annotation(com.xx.yy.apsect.VerifyAuthority) ")
    public void pointCut() {
    }


    @Around("pointCut()")
    public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
        
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取注解
VerifyAuthority dgrb = methodSignature.getMethod().getAnnotation(VerifyAuthority.class);
        Object[] args = joinPoint.getArgs();

        //获取入参
        Map<String, Object> paramMap = (Map<String, Object>) args[0];

        //如果注解里面的值是我设置的话,这里写需要增加的逻辑
        if (VerifyAuthorityElement.DGRB.equals(dgrb.value())) {
            ......
        }
       //返回主流程,让他继续执行
        return joinPoint.proceed();
        //因为用的around,所以在 joinPoint.proceed()执行完,还可以增加处理逻辑的
    }

 

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值