天天看點

Spring-AOP簡單使用方法

顧名思義 AOP(Aspect oriented Programming)字面意思是面向切面程式設計,aop所帶來的好處是能提取具有共同功能的代碼塊,比如使用者取款流程需要用到1.使用者密碼的驗證;2.使用者查詢餘額需要用到密碼的驗證 那麼兩者之間的共同密碼驗證功能的邏輯實作則可以提取出來,提取出來的部分稱為切面。以下為aop的小小案例(有兩個HelloWord類,它們都需要列印時間毫秒,那麼我們可以抽取列印時間作為切面)

1.操作AOP需要用到的jar包為

Spring-AOP簡單使用方法

2.建立HellWord的接口,聲明兩個方法sayHello()dopoint()

package com.aop;

public interface HelloWord {
	public void sayHello();
	public void dopoint();

}
           

3.分别實作HellWord接口

package com.aop.hw;

import com.aop.HelloWord;

public class HelloWordImp2 implements HelloWord {

	@Override
	public void sayHello() {
		System.out.println("我是HelloWord2");
		
	}

	@Override
	public void dopoint() {
		System.out.println("我是dopoint2");
	}
  
}
           
package com.aop.hw;

import com.aop.HelloWord;
public class HelloWordImp1 implements HelloWord {

	@Override
	public void sayHello() {
		System.out.println("我是HelloWord1");
	}

	@Override
	public void dopoint() {
		System.out.println("我是dopoint1");
	}

}
           

4.建立一個時間切面TimerAspect類

package com.aop;

public class TimerAspect {
   public void timer() {
	   System.out.println(System.currentTimeMillis());
   }
}
           

5.配置applicationContext.xml檔案,注意在配置xml檔案的時候,這裡expression="execution(* com.aop.hw.*.*(..))"需要注意,兩個.*.*代表的是包下的類下的所有方法,<aop:config  proxy-target-class="true">這條語句中的proxy-target-calss=“true”需要加入,否則報錯

<?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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
            
            
            <bean id="hello1" class="com.aop.hw.HelloWordImp1"></bean>
            <bean id="hello2" class="com.aop.hw.HelloWordImp2"></bean>
            <bean id="timerAspect" class="com.aop.TimerAspect"></bean>
           
           <aop:config  proxy-target-class="true">
              <aop:aspect id="timer" ref="timerAspect">
                 <aop:pointcut id="addAllMethod"  expression="execution(* com.aop.hw.*.*(..))" />
                 <aop:before method="timer" pointcut-ref="addAllMethod" />
                 <aop:after method="timer" pointcut-ref="addAllMethod" />
                 
              </aop:aspect>
           </aop:config>
</beans>


           
Spring-AOP簡單使用方法