文章目录
1.什么是AOP切面编程?
AOP(Aspect oriented Programming):就像是一些插件,像横切面一样横切在运行程序中,不想要了可用通过配置文件随时取掉,所以把这项技术叫面向切面编程
优点是:不修改源码的情况下对程序进行扩展
2.AOP的关键概念
##2.1 Spring AOP和AspectJ的关系
Eclipse AspectJ一种基于java平台的面向切面变成的语言 Spring AOP使用Aspectweaver实现类和方法匹配
Spring AOP利用代理模式实现对象运行时功能扩展
关键概念:
Aspect:切面,具体可插拔组件功能类,通常一个切面只实现一个通用功能
TargetClass/Method:目标类,目标方法,指真正要执行业务相关的方法
PointCut:切入点,使用execution表达式说明切面作用在哪些系统的哪些类上
JoinPoint:链接点,切面运行过程中是包含目标类/方法元数据的对象
Advice:通知,说明具体的切面的执行时机,Spring包含了五种不同类型的通知
3.如何使用AOP切面编程技术
3.1 依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
<!--spring-context中已经包含了aop依赖-->
</dependency>
<dependency>
<!--aspectjweaver是spring aop的底层依赖-->
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
3.2 创建一个切面类(Aspect)
代码演示:
public class MethodAspect {
//切面方法,用于扩展额外功能
//JoinPoint 连接点,通过连接点可以获取目标类/方法的信息
public void printExecutionTime(JoinPoint joinPoint){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String now = sdf.format(new Date());
String className = joinPoint.getTarget().getClass().getName();//获取目标类的名称
String methodName = joinPoint.getSignature().getName();//获取目标方法名称
System.out.println("---->" + now + ":" + className + "." + methodName);
Object[] args = joinPoint.getArgs();
System.out.println("---->参数个数:" + args.length);
for(Object arg:args){
System.out.println("---->参数:" + arg);
}
}
public void doAfterReturning(JoinPoint joinPoint,Object ret){
System.out.println("<----返回后通知:" + ret);
}
public void doAfterThrowing(JoinPoint joinPoint,Throwable th){
System.out.println("<----异常通知:" + th.getMessage());
}
public void doAfter(JoinPoint joinPoint){
System.out.println