SpringBoot中自定义注解
平常的工作中总会有一些事情是重复的,比如接口的风控验证等。这些东西都是可以通过注解来实现,使得代码更加简洁优雅。
1 引入依赖
<!--aop切面-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2 增加注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "wyf";
}
注解中需要使用到一些元注解,特别是@Target和@Retention
@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) ///包
@Retention:
- @Retention(RetentionPolicy.SOURCE) —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
- @Retention(RetentionPolicy.CLASS) —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
- @Retention(RetentionPolicy.RUNTIME) —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.
3 增加切面
package com.example.annotationdemo.aspects;
import com.example.annotationdemo.annotations.MyAnnotation;
import lombok.extern.slf4j.Slf4j;
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.stereotype.Component;
@Aspect
@Component
@Slf4j
public class MyAnnotationAspect {
@Pointcut("@annotation(com.example.annotationdemo.annotations.MyAnnotation)")
public void pointCut() {
}
@Before("pointCut()")
public void before(JoinPoint joinPoint) throws NoSuchMethodException {
log.info("==================前置执行=====================>");
MyAnnotation annotation = joinPoint.getTarget().getClass().getMethod("test", String.class, String.class).getAnnotation(MyAnnotation.class);
System.out.println(annotation.value());
log.info("==================前置执行完成==================>");
}
}
在切面中使用反射拿到对应方法上,或者类上(具体还需要看注解需要用在什么上面)的注解,以及注解的属性,然后对其做一些处理。
因为使用到了SpringBoot,所以使用自定义注解的类也需要注入到IOC中。
参考链接:
评论区