javascript
java 环绕通知_SpringAOP四种通知类型+环绕通知
SpringAOP的四種通知類型:前置通知、異常通知、后置通知、異常通知
一、四種常見的通知類型
給出 賬戶的業務層接口 IAccountService.java,
為了便于演示這四種通知類型,我們就只留下了一個方法。
public interface IAccountService {
void saveAccount();
}
給出 賬戶的業務層接口的實現類 AccountServiceImpl.java
public class AccountServiceImpl implements IAccountService{
@Override
public void saveAccount() {
System.out.println("執行了保存");
//int i=1/0;
}
}
給出一個日志類, 用于打印日志
public class Logger {
/**
* 前置通知
*/
public void beforePrintLog(){
System.out.println("前置通知Logger類中的beforePrintLog方法開始記錄日志了。。。");
}
/**
* 后置通知
*/
public void afterReturningPrintLog(){
System.out.println("后置通知Logger類中的afterReturningPrintLog方法開始記錄日志了。。。");
}
/**
* 異常通知
*/
public void afterThrowingPrintLog(){
System.out.println("異常通知Logger類中的afterThrowingPrintLog方法開始記錄日志了。。。");
}
/**
* 最終通知
*/
public void afterPrintLog(){
System.out.println("最終通知Logger類中的afterPrintLog方法開始記錄日志了。。。");
}
}
給出配置信息bean.xml
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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
注意:
1)異常通知和后置通知永遠只能執行一個
2)配置切入點表達式
此標簽寫在aop:aspect標簽內部只能當前切面使用。
它還可以寫在aop:aspect外面,此時就變成了所有切面可用
給出Test類
public class AOPTest {
public static void main(String[] args) {
//1.獲取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.獲取對象
IAccountService as = (IAccountService)ac.getBean("accountService");
//3.執行方法
as.saveAccount();
}
}
執行結果:
當我們放開AccountServiceImpl類中我們故意制造的異常 int i=1/0;時:
二、環繞通知
環繞通知,只需要稍稍微改變上面例子的兩點即可
(1)改動日志類 Logger.java
public class Logger {
public Object aroundPringLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs();//得到方法執行所需的參數
System.out.println("Logger類中的aroundPringLog方法開始記錄日志了。。。前置");
rtValue = pjp.proceed(args);//明確調用業務層方法(切入點方法)
System.out.println("Logger類中的aroundPringLog方法開始記錄日志了。。。后置");
return rtValue;
}catch (Throwable t){
System.out.println("Logger類中的aroundPringLog方法開始記錄日志了。。。異常");
throw new RuntimeException(t);
}finally {
System.out.println("Logger類中的aroundPringLog方法開始記錄日志了。。。最終");
}
}
}
注意:pjp.proceed(args)會報異常,必須用 Throwable t,因為Exception攔不住它
(2)改動配置文件
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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
分析:
spring中的環繞通知是spring框架為我們提供的一種可以在代碼中手動控制增強方法何時執行的方式。
Spring框架為我們提供了一個接口:ProceedingJoinPoint。該接口有一個方法proceed(),此方法就相當于明確調用切入點方法。該接口可以作為環繞通知的方法參數,在程序執行時,spring框架會為我們提供該接口的實現類供我們使用。
總結
以上是生活随笔為你收集整理的java 环绕通知_SpringAOP四种通知类型+环绕通知的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab 遥感图像分类,彩色遥感图像
- 下一篇: PID LSim PT3这个仿真模块 S