spring boot 注解+AOP

引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

创建注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CheckVerifyType {

    String tableName();
}

tableName可以使注解参数,可以不填。

填写的话需要在引用注解的时候补充这个参数,当然,可以给这个参数设置默认值,比如

@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CheckVerifyType {

    String tableName() default "t_aaa";
}

创建注解切面,处理逻辑。

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.stereotype.Component;
import java.lang.reflect.Method;

/**
 * @author wsz
 * @date 2022/04/27 11:22
 * @desc 测试申请、测试计划输入参数类型校验
 */
@Aspect
@Component
public class CheckVerifyTypeAOP {

    @Pointcut("@annotation(cnki.tpi.annotation.CheckVerifyType)")
    public void pointCut(){

    }

    @Around("pointCut()")
    public Object checkTokenAroundAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取参数rableName
        Class<?> targetClass = joinPoint.getTarget().getClass();
        MethodSignature ms = (MethodSignature)joinPoint.getSignature();
        Method targetMethod = targetClass.getDeclaredMethod(ms.getName(), ms.getParameterTypes());
        CheckVerifyType annotation = targetMethod.getAnnotation(CheckVerifyType.class);
        String tableName = annotation.tableName();

        //获取入参
        Object dto =joinPoint.getArgs()[0];
        // todo 处理执行方法之前需实现的逻辑
        // do something
        //执行原本的逻辑
        joinPoint.proceed();
        // todo 处理执行方法之后需实现的逻辑,一般是处理返回值
        // do something
        return "hello world";
    }


}

在需要使用的方法上引用注解。

    /**
     * 提交测试申请
     */
    @Override
    @CheckVerifyType(tableName = "t_aaa")
    public Integer insert(TestSubmitAdditionalDTO info) {
        return count = testApplyMapper.insert(info);
    }

 

posted @ 2022-04-28 14:03  代码羡  阅读(199)  评论(0编辑  收藏  举报