今天學習《Spring實戰》第4章《面向切面的Spring》,根據4.3.3小節寫出以下切面類:java
package proxy; import java.util.HashMap; import java.util.Map; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Component @Aspect public class Audience { private Map<Integer, Integer> trackCounts = new HashMap<>(); @Pointcut("execution(** concert.JayPerform.playTrack(int)) && args(trackNum)") //<1> public void track(int trackNum) {} //<2> @AfterReturning("track(trackNum)") //<3> public void countTrack(int trackNum) //<4> { int currentCount = getPlayCount(trackNum); trackCounts.put(trackNum, currentCount+1); System.out.println("------- 這首歌播放了"+(currentCount+1)+"次"); } public int getPlayCount(int trackNumber) { return trackCounts.containsKey(trackNumber)?trackCounts.get(trackNumber):0; } }
代碼中 <1>、<2>、<3>、<4> 處,int型參數的名稱都是trackNum,這樣保證了從命名切點到通知方法的參數轉移。而且,這裏的參數trackNum與concert.JayPerform.playTrack(int trackNum) 的參數命名相同。
通過實驗,發現這4處的參數名稱與concert.JayPerform.playTrack(int trackNum)中的參數名稱沒必要相同,只要<1>與<2>處參數名稱相同、<3>與<4>處參數名稱相同便可。這四處代碼可修改以下:spring
package proxy; import java.util.HashMap; import java.util.Map; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Component @Aspect public class Audience { private Map<Integer, Integer> trackCounts = new HashMap<>(); @Pointcut("execution(** concert.JayPerform.playTrack(int)) && args(num1)") //<1> public void track(int num1) {} //<2> @AfterReturning("track(val1)") //<3> public void countTrack(int val1) //<4> { int currentCount = getPlayCount(val1); trackCounts.put(val1, currentCount+1); System.out.println("------- 這首歌播放了"+(currentCount+1)+"次"); } public int getPlayCount(int trackNumber) { return trackCounts.containsKey(trackNumber)?trackCounts.get(trackNumber):0; } }