一、AOP代码实现
需求:在不改动业务逻辑类的基础上实现在原有代码之前之后分别加上新的功能及异常处理。
-
导包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>springcode</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.6.RELEASE</version> </dependency> <!-- 切面 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.1.14.RELEASE</version> </dependency> </dependencies> </project>
-
定义业务逻辑类
package org.example.bean.aop; /** * @author JHS */ public class Business { public int show(int i,int j) { System.out.println("这是主要的业务逻辑功能模块"); return i/j; } }
-
定义一个新功能切面类
package org.example.bean.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import java.util.Arrays;
/**
* @Aspect 告诉spring这是一个切面类
* @author JHS
*/
@Aspect
public class AspectAdd {
//抽取公共的切入表达式
@Pointcut("execution(public int org.example.bean.aop.Business.*(..))")
public void pointCut(){}
//前置通知
//@Before在目标方法之前切入,切入表达式(访问修饰符 返回值 全限定类名.方法名(参数)) */.. 任意方法/参数
@Before("pointCut()")
public void before(){
System.out.println("新功能前---hello!");
}
//返回通知
@AfterReturning(value = "pointCut()",returning = "result")
public void common(Object result){
System.out.println("正常返回"+result);
}
//后置通知
//JoinPoint需在参数列表第一位
@After("pointCut()")
public void after(JoinPoint joinPoint){
//接受参数
Object[] args = joinPoint.getArgs();
System.out.println("新功能后---ByeBye!"+ Arrays.toString(args));
}
//异常通知
@AfterThrowing(value = "pointCut()",throwing = "exception")
public void exception(Exception exception){
System.out.println("异常"+exception);
}
}
结果: