必要的依赖包
在pom.xml中添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
输入日志注解
这里定义一个实现日志输出的注解:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLogAnnotation {
}
定义切面类
定义一个切面类用于匹配自定义的注解:
@Configuration
@Aspect
@Slf4j
public class MyLogAnnotationAopConfig {
//通过@within和@annotation保证注解使用在类和方法上都能正常工作
@Around(value = "@within(com.example.aop.annotation.MyLogAnnotation)||@annotation(com.example.aop.annotation.MyLogAnnotation)")
public void doAround(ProceedingJoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
//方法执行之前
log.info("准备执行 " + methodName + " 方法");
try {
//执行方法
joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
//方法执行之后
log.info(methodName + " 方法已执行完毕");
}
}
定义控制层
此处定义一个控制层对外提供API接口调用:
@RestController
@RequestMapping("/")
@Slf4j
@MyLogAnnotation //在类型上使用自定义注解
public class AopController {
@GetMapping("/test1")
public void test1() {
log.info("执行 test1 方法");
}
@GetMapping("/test2")
public void test2() {
log.info("执行 test2 方法");
}
}
测试结果
在浏览器分别输入http://localhost:8100/test1和http://localhost:8100/test2查看日志输出结果: