天天看點

Spring_AOP學習筆記

概念:AOP(Aspect Oriented Programming)是一種面向切面的程式設計。比如當我們需要在一個已有的系統中添加日志,就需要到各個子產品的控制層或是實作層添加代碼,這樣開發效率極低,并且代碼備援。如果利用AOP,就相當于,在所有的控制層上,劃分出一個切面,這個切面定義了日志記錄,所有經過控制層的代碼,都會通過切面進行日志儲存。

執行個體:

一 在配置檔案中配置AOP

<!-- 開啟aop -->
    <aop:aspectj-autoproxy expose-proxy="true"></aop:aspectj-autoproxy>
    
    <!-- 測試aop -->
    <bean id="transactionDemo" class="com.yy.student.test.TransactionDemo"></bean>
    
    <aop:config>
        <aop:pointcut expression="execution(* com.yy.student.service.*.*(..))" id="p1" />   //execution定義了切面攔截的地方,特别注意*号後面有一個空格

        <aop:aspect ref = "transactionDemo">     
        
        <aop:before method="startTransaction" pointcut-ref="p1" />   //前置方法
        
        <aop:after-returning method="commitTransaction" pointcut-ref="p1"/>      //後置方法
        
        </aop:aspect>
    </aop:config>
           

二 添加切面代碼

public class TransactionDemo {
	
	//前置
	public void startTransaction(){
		System.out.println("=======前置代碼========");
	}
	
	//後置
	public void commitTransaction(){
		System.out.println("=======後置代碼========");
	}

}
           

三 xml檔案加入aop

xmlns:aop="http://www.springframework.org/schema/aop" 


http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
           
Spring_AOP學習筆記

配置結束就可以測試啦,如果測試不成功,可以參考下面的方法:

Spring啟動時會先加載Spring-mvc的配置檔案,再加載Spring的配置檔案,如果你的AOP配置攔截service層,那麼如果寫到Speing-mvc的配置檔案中,是不起作用的。Spring-mvc配置檔案隻掃描控制層,而service層沒有被注冊,是以此時配置的AOP是無效的。

如果這樣也沒有解決,那麼百度吧