我们知道,AOP是Spring Framework的两大特性之一,AOP通俗地讲就是可以实现对方法的增强,并且是以代码侵入性低的方式。其底层实现基于动态代理,如果代理对象没有实现某个接口,那么会用jdk代理,如果实现了某个接口,就用CGlib
AOP的一个很常见的使用场景就是日志
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
代码
实现AOP有多种方式,这里我们用最常用的一种,即基于注解的方式
定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
String operation() default "";
}
给需要增强的方法添加注解
@LogAnnotation(operation = "简单介绍")
public ResponseResult method(){
return ResponseResult.okResult();
}
写切面类
@Pointcut的属