一、定義一個切面
package com.xiao.aop;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
@Aspect
public class AopAspect {
@Pointcut("execution(* com.xiao.aop.MathDemo.*(..))")
public void poincut(){}
@Before("poincut()")
public void before(JoinPoint joinPoint){
System.out.println("Before 開始 參數"+ JSONObject.toJSONString(joinPoint.getArgs()));
}
@After("poincut()")
public void after(JoinPoint joinPoint){
System.out.println("After 最終通知 參數"+ JSONObject.toJSONString(joinPoint.getArgs()));
}
@AfterReturning(value="poincut()",returning ="i")
public void afterReturning(JoinPoint joinPoint,int i){
System.out.println("AfterReturning 方法正常返回通知 參數"+ JSONObject.toJSONString(joinPoint.getArgs())+"返回結果 "+i);
}
@Around("poincut()")
public int around(ProceedingJoinPoint point) throws Throwable {
System.out.println("around 環繞開始");
int proceed = (int) point.proceed();
System.out.println("around 環繞結束");
return proceed;
}
@AfterThrowing(value="poincut()",throwing = "exception")
public void afterThrowing(JoinPoint joinPoint,RuntimeException exception){
System.out.println("AfterThrowing "+joinPoint.getSignature().getName()+"異常信息是:{"+exception+"}");
}
}
二、定義一個配置類
package com.xiao.aop;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("com.xiao.aop")
@EnableAspectJAutoProxy
public class AopConfig {
@Bean
public MathDemo getMathDemo(){
return new MathDemo();
}
@Bean
public AopAspect getAopAspect(){
return new AopAspect();
}
}
三、定一個計算類
package com.xiao.aop;
public class MathDemo {
public int div(int i,int j){
return i/j;
}
}
四、定義一個測試類
package com.xiao.aop;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestAop {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
MathDemo bean = context.getBean(MathDemo.class);
System.out.println( bean.div(2, 2));
}
}
五、正常執行結果
around 環繞開始
Before 開始 參數[2,2]
around 環繞結束
After 最終通知 參數[2,2]
AfterReturning 方法正常返回通知 參數[2,2]返回結果 1
1
六、異常執行結果
around 環繞開始
Before 開始 參數[2,0]
After 最終通知 參數[2,0]
AfterThrowing div異常信息是:{java.lang.ArithmeticException: / by zero}
Exception in thread "main" java.lang.ArithmeticException: / by zero
七 、注意點
1、AfterReturning 只有正常結束才執行 After 不管正常還是異常結束都會執行
因爲源碼中After是放在finally代碼塊中 所以不管正常還是異常結束都會執行,而AfterReturning 是在return 語句中返回 所以只有在正常結束才能執行
由於After在finally代碼塊中 而AfterReturning 在retrun語句中返回的 所以 After要先執行 AfterReturning 後執行
2、可以再around環繞通知中 改變返回的結果