@Target
@Retention
@Documented
@Aspect
1、添加依赖
首先在pom文件中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2、定义一个注解
按照下图进行选择创建注解类
代码如下
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnnotationTest {
}
3、定义注解的具体实现类
测试代码如下
@Aspect
@Component
public class AnnotationTestAspect {
@Pointcut("@annotation(com.example.demo.annotation.AnnotationTest)")
public void point(){
System.out.println("12");
}
@Before("point()")
public void before(){
System.out.println("begin");
}
@AfterReturning("point()")
public void after(){
System.out.println("commit");
}
@Around("point()")
public void around(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("around begin");
joinPoint.proceed();
System.out.println("around commit");
}
}
4、在实际应用中使用注解
@AnnotationTest
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ApiOperation(value = "测试", notes = "测试", httpMethod = "GET")
public String test(){
return "success";
}
调用接口http://localhost:9999/test
控制台中输出如下图所示:
至此,一个简单的自定义注解就完成了
关于@Target @Retention @Documented这几个注解可以查看一下这个文件
https://blog.csdn.net/liang100k/article/details/79515910