Spring的AOP
SpringBoot提供的AOP
@Before 前置通知:在方法执行前执行
@AfterReturning 返回通知 :在方法正常结束后执行
@AfterThrowing 异常通知:在方法抛出异常后执行
@After 最终通知:在方法执行后,不管是否有异常执行
@Around 环绕通知:环绕通知方法可以包含上面四种通知方法,功能最全面
SpringBoot自定义AOP步骤
-
定义切面Aspect
-
定义切点Pointcut
-
添加通知Advice
-
连接点Joinpoint 加强
@Component
@Aspect
public class CustomAspect {
@Pointcut("execution(* com.xuyuan.service..*(..))")
public void point() {
}
@Pointcut("@annotation(com.xuyuan.spring.aop.AfterResponse)")
public void point1() {
}
@Before("point()")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Parameter[] parameters = signature.getMethod().getParameters();
if (parameters.length < 2) ;
System.out.println("before");
}
@After("point1()")
public void after(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Parameter[] parameters = signature.getMethod().getParameters();
if (parameters.length < 2) ;
System.out.println("after");
}
}
AspectJ 和 Spring AOP 的区别
目标不同:
SpringAOP是spring支持的面向切面AOP编程的一个工具。
AspectJ是一个面向切面的框架,它扩展了Java语言。AspectJ定义了AOP语法,它有一个专门的编译器用来生成遵守Java字节编码规范的Class文件。
织入方式不同:
AspectJ 使用了三种不同类型的织入方式:
Compile-time weaving:编译期织入。编译器将切面和应用的源代码编译在一个字节码文件中。
Post-compile weaving:编译后织入。也称为二进制织入。将已有的字节码文件与切面编制在一起。
Load-time weaving:加载时织入。与编译后织入一样,只是织入时间会推迟到类加载到jvm时。
SpringAOP使用运行时织入
连接点不同:
springAOP 只支持方法执行连接点,而ASpectJ 还支持 方法调用,构造方法调用,属性引用,静态初始化、其他切面的通知等 作为连接点。 功能相当强大。
性能不同:
编译期织入要比运行期织入快很多。因此aspectJ 的运行速度要快于springAOP、