前提准备:
pom.xml:
<!-- ######################引入spiring AOP############################################# -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop
已经被其它依赖引入:可以不配置
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt
import org.aspectj.lang.annotation.Aspect
用于@Aspect
-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver
Aspect的依赖包
-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.1</version>
</dependency>
applicationContext.xml:增加启用aop
<aop:aspectj-autoproxy />
aop类:拦截任意返回类型,在com.chenxf.test下的包、子包的所有类的任意参数的所有方法,需要@Aspect @Component
package com.chenxf.AOP;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AspectJForTest {
@Pointcut("execution(* com.chenxf.test..*.*(..))")
private void execute(){}
@Before("execute()")
public void b(){
System.out.println("Before...1");
}
@After("execute()")
public void a(){
System.out.println("After...2");
}
@AfterReturning("execute()")
public void ar(){
System.out.println("AfterReturning...3");
}
@AfterThrowing("execute()")
public void at(){
System.out.println("AfterThrowing...4");
}
@Around("execute()")
public void around(ProceedingJoinPoint pjp){
try{
System.out.println("Around....a");
pjp.proceed();
System.out.println("Around....b");
}catch (Exception e){
System.out.println("Around....c");
e.printStackTrace();
} catch (Throwable throwable) {
System.out.println("Around....d");
throwable.printStackTrace();
}
}
}
测试代码:
// 单独测试applicationContext.xml
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AopTest aopTest = (AopTest) context.getBean("aopTest");
aopTest.a();
System.out.println("-------------------------test...c");
aopTest.c();
三种输出情况:
在只使用@Around 的输出,Around...c这个是 异常方法里的
只使用:@Before、@After、@AfterReturning、@AfterThrowing的输出
两种一超 使用的情况:@AfterThrowing的异常处理不见了,优先被@Around的处理