Spring中基於aop命名空間的AOP 一(一點準備工作和一個例子)

來源:互聯網
上載者:User

在某些時候,我們工程中使用的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;
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.