五分鐘掌握springAop
阿新 • • 發佈:2019-02-07
前言:所有demo都是基於maven!所有知識點都有demo程式碼做案例!
為什麼用springAop
因為springAop為業務模組所共同呼叫的邏輯封裝起來,便於減少系統的重複程式碼,降低模組之間的耦合度,增加系統的可維護性。
快速入門案例
定義一個介面
package com.test;
public interface Student {
public void saveStudent();
}
實現介面
package com.test;
public class StudentImpl implements Student {
public void saveStudent() {
System.out.println("save student");
}
}
定義一個切面
package com.test;
//切面
public class Aspect {
public void begincommit(){
System.out.println("before commit");
}
}
xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd" >
<bean id="student" class="com.test.StudentImpl"></bean>
<bean id="aspect" class="com.test.Aspect"></bean>
<aop:config>
<!-- 切入點表示式 確定目標類 -->
<aop:pointcut expression="execution(* com.test.StudentImpl.*(..))" id="perform"/>
<!-- ref指向的物件就是切面-->
<aop:aspect ref="aspect">
<aop:before method="begincommit" pointcut-ref="perform"/>
</aop:aspect>
</aop:config>
</beans>
測試類
package com.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AspectTest {
@Test
public void testAspect(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student)context.getBean("student");
student.saveStudent();
}
}
測試執行結果
簡單講解
從例子上可以看出我們僅僅呼叫了student.saveStudent()這個方法,控制檯缺打印出了”before commit”這個東西。如果沒有srpingaop我們要在saveStudent之前要呼叫某一個類,必須得寫一個工具類去呼叫。有了springaop之後我們不需要自己去呼叫,只需要在配置檔案配置下就可以。程式中如果有需要共同呼叫的模組,就可以定義一個切面,統一呼叫,程式碼耦合度就低了不少。例子僅僅用了”前置通知”做案例,如有興趣繼續掌握請看下面知識擴充!
知識擴充
springAop各種通知
前置通知(before):在目標方法執行之前執行
後置通知(after):在目標方執行完成後執行,如果目標方法異常,則後置通知不再執行
異常通知(After-throwing):目標方法丟擲異常的時候執行
最終通知(finally);不管目標方法是否有異常都會執行,相當於try…..catch….finally中的finally
環繞通知(round):可以控制目標方法是否執行
重點掌握前置通知、後置通知與環繞通知的區別。
下面會有程式碼連線,具體請執行程式碼示例。
springAop註解形式
springAop目前支援兩種實現方式,一個是基於xml實現,一個是基於註解方式實現,下面會有程式碼連線,具體請參考程式碼示例。