SpringBoot自定义注解和aop

自定义注解类编写的一些规则:

1定义一个注解Annotation

定义为@interface,所有的Annotation会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是接口。

参数成员只能用public或默认(default)这两个访问权修饰。

参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和String、Enum、Class、annotations等数据类型,以及这一些类型的数组

package com.success.access.audit.annotation;

import ...
/**
 * 接口访问控制注解
 */
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface AccessAuditAnnotation {
        /** 日志模块*/
        String moduleCode();
        /**日志模块*/
        String module();
        /**记录参数*/
        boolean recordParam() default true;
}

@Retention 注解:指明修饰的注解的生存周期,即会保留到哪个阶段。
RetentionPolicy的取值包含以下三种:
@Retention(RetentionPolicy.SOURCE) —— 这种类型的Annotations只在源码级别保留,编译后即丢弃;

@Retention(RetentionPolicy.CLASS) —— 这种类型的Annotations编译级别保留,编译后的class文件中存在,在jvm运行时丢弃
@Retention(RetentionPolicy.RUNTIME) —— 这种类型的Annotations运行级别保留,编译后的class文件中存在,在jvm运行时保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用

@Target 注解:

@Target(ElementType.TYPE) //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包

@Aspect//将一个类定义为一个切面类

@Pointcut//定义需要切面的地方,表达式参数(https://blog.csdn.net/elim168/article/details/78150438)

@annotation//匹配注解,当执行的方法上拥有指定的注解时生效。

几个注解的解释
@Around 环绕切点,在进入切点前,跟切点后执行

@After 在切点后,return前执行,

@Before 在切点前执行方法,内容为指定的切点

2定义一个aop类

package com.success.access.audit.aop;

import ...

/**
 * 权限访问控制
 */
@Aspect
@Component
@Slf4j
public class AccessAuditAop {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 环绕带注解 @AccessAuditAnnotation的方法做aop
     */
    @Around(value = "@annotation(com.success.access.audit.annotation.AccessAuditAnnotation)")
    public Object accessAuditCheck(ProceedingJoinPoint joinPoint) throws Throwable {
        //具体的方法逻辑
    }
}

3使用

在Controller的每个接口上增加注解@AccessAuditAnnotation(moduleCode = "RY", module = "人员"),这样在调用接口的时候,会先走aop方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值