Spring AOP
前言:spring的两大核心是IOC和AOP
IOC:控制反转,把对象交给spring统一管理,不需要自己手动new
AOP:面向切面编程,在不改变原代码的基础上对方法进行增强
依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
AOP切点模板
package com.jzlw.goodluckway.log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
/**
* 切点表达式:execution(* com.jzlw.goodluckway.service..*(..))
*/
@Component
@Aspect
public class LogUtil {
@Pointcut("execution(* com.jzlw.goodluckway.service..*(..))")
public void pointcut() {
}
@Before("pointcut()")
public static void before(JoinPoint joinPoint) {
//方法名
String method = joinPoint.getSignature().getName();
//参数
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println(method + "方法运行,参数是:" + args);
}
@After("pointcut()")
public static void after() {
//System.out.println("方法后");
}
@AfterThrowing(value = "pointcut()", throwing = "ex")
public static void afterException(Exception ex) {
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw, true));
System.out.println("异常通知:" + sw.getBuffer().toString());
}
@AfterReturning("execution(* com.jzlw.goodluckway.service..*(..))")
public static void afterReturning() {
//System.out.println("方法返回后");
}
//@Around("execution(* com.jzlw.goodluckway.service..*(..))")
public static void around() {
System.out.println("环绕");
}
}
总结:AOP主要用于对现有代码进行增强,一般多用于线上查看打印日志,aop是基于代理的.
静态代理:需要给每个被代理对象创建代理类
jdk动态代理:被代理对象需要实现接口
cglib动态代理:被代理对象不实现接口,但是要继承该接口的一个实现类