在某些時候,我們工程中使用的JDK 不一定就是1.5 以上,也就是說可能不支援Annotation 註解,這時自然也就不能使用@AspectJ 註解驅動的AOP 了,那麼如果我們仍然想使用AspectJ 靈活的切入點運算式,那麼該如何呢?Spring 為我們提供了基於xml schematic 的aop 命名空間,它的使用方式和@AspectJ 註解類似,不同的是配置資訊從註解中轉移到了Spring 設定檔中。在這裡,我們將詳細介紹如何使用Spring 提供的<aop:config/> 標籤來配置Spring AOP 。
1 、一點準備工作和一個例子
使用<aop:config/> 標籤,需要給Spring 設定檔中引入基於xml schema 的Spring AOP 命名空間。完成後的Spring 設定檔如下(在該節,所有常式的設定檔中添加了Spring AOP 命名空間,除非特殊情況外,為了節約空間,這部分將在給出的代碼中省略),粗體內容即為我們需要添加的內容:
代碼
<?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
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 >
………… Spring配置資訊
</beans>
關於aop命名空間的標籤,我們前面使用過的有<aop:aspectj-autoproxy/>,在這一節,我們將以<aop:config/>標籤作為重點。事實上,我們在這一節介紹的所有標籤都是該標籤的子標籤。
下面有一個常式來直觀的展示如何使用<aop:config/>標籤來配置Spring AOP(完整代碼見常式4.15)。在例子中,我們使用<aop:config/>配置一個切面並攔截目標對象Peoples的SayHello()方法,在它執行前輸出提示資訊。
首先建立工程AOP_Test4.15,添加Spring IoC和Spring AOP庫後,建立aop.test包,建立目標類People,代碼如下:
代碼
package aop.test;
/**
* 該類將作為目標對象對應的類。
* @author zhangyong
* */
public class People{
public String SayHello(String str){
System.out.println(this.getClass().getName()+ "說:"+str);
return str;
}
}