《Spring实战》第4章--面向切面的Spring--处理通知中的参数(经验总结)

时间:2022-04-27 23:03:51

今天学习《Spring实战》第4章《面向切面的Spring》,根据4.3.3小节写出如下切面类:

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>处参数名称相同即可。这四处代码可修改如下:

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;
} }