本文主要是對於spring aop簡單入門做一些介紹,並不深入瞭解,只接觸表面,對一些較複雜的內容也不過多描述。如文中有錯誤之處,望不吝賜教,謝謝~
一、AOP常用通知類型
- 前置通知
在切入點方法執行之前執行執行的通知。 - 後置通知
在切入點方法執行之後執行執行的通知。 - 異常通知
在切入點方法執行之後發生異常執行的通知(注意後置通知和異常通知同時只存在一個)。 - 最終通知
在切入點方法執行之後執行執行的通知。
和後置通知不同之處在於,後置通知是在方法正常返回後執行的通知,如果方法沒有正常返回,例如拋出異常,則後置通知不會執行。而最終通知無論如何都會在目標方法調用過後執行,即使目標方法沒有正常的執行完成。 - 環繞通知
在切入點方法執行之前和之後都可以執行額外代碼的通知,根據這一特性,可以藉助環繞通知實現其他四種通知。
二、實例
在上一篇文章Spring AOP簡單入門學習(一)的項目基礎上進行展開。
(1)修改Logger.java
package com.example.utils;
public class Logger {
/**
* 前置通知
*/
public void beforePrintLog(){
System.out.println("打印日誌-前置通知");
}
/**
* 後置通知
*/
public void afterReturningPrintLog(){
System.out.println("打印日誌-後置通知");
}
/**
* 異常通知
*/
public void afterThrowingPrintLog(){
System.out.println("打印日誌-異常通知");
}
/**
* 最終通知
*/
public void afterPrintLog(){
System.out.println("打印日誌-最終通知");
}
}
(2)修改bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置ioc-->
<bean id="userService" class="com.example.service.impl.UserServiceImpl"/>
<bean id="logger" class="com.example.utils.Logger"/>
<!--配置aop-->
<aop:config>
<!--配置切面 id提供唯一標識 ref指定某一bean-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置前置通知 -->
<aop:before method="beforePrintLog"
pointcut="execution(* com.example.service.impl.*.*(..))"/>
<!--配置後置通知 -->
<aop:after-returning method="afterReturningPrintLog"
pointcut="execution(* com.example.service.impl.*.*(..))"/>
<!--配置異常通知 -->
<aop:after-throwing method="afterThrowingPrintLog"
pointcut="execution(* com.example.service.impl.*.*(..))"/>
<!--配置最終通知 -->
<aop:after method="afterPrintLog"
pointcut="execution(* com.example.service.impl.*.*(..))"/>
</aop:aspect>
</aop:config>
</beans>
(3)在saveUser()裏面構造一個異常的語句
int i=1/0;
(4)執行AopTest,結果如下
測試成功。注意後置通知和異常通知同時只能有一個執行。
(5)在Logger.java裏面添加環繞通知方法
/**
* 環繞通知
*/
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object returnValue=null;
try {
Object[] args=pjp.getArgs();
System.out.println("打印日誌-環繞通知-前置通知");
returnValue=pjp.proceed(args);
System.out.println("打印日誌-環繞通知-後置通知");
return returnValue;
}catch (Throwable throwable) {
System.out.println("打印日誌-環繞通知-異常通知");
throwable.printStackTrace();
throw new RuntimeException(throwable);
}finally {
System.out.println("打印日誌-環繞通知-最終通知");
}
}
(6)在bean.xml中配置環繞通知
<!--配置環繞通知 -->
<aop:around method="aroundPrintLog"
pointcut="execution(* com.example.service.impl.*.*(..))"/>
(7)執行AopTest,結果如下:
2020.03.21