目錄
- 文件目錄
- 切點表達(dá)式
- 源碼
- 測試
- 測試效果
文件目錄
soundsystem
|- ConcertConfig
|- CompackDisc
|- TrackCounter
切點表達(dá)式
返回任意類型 方法所屬的類型 方法 接受int類型的參數(shù)
|-||---------------------| |-------||---|
execution(* soundsystem.CompactDisc.playTrack(int)) && args(trackNumber)
|---------------|
指定參數(shù)
源碼
ConcertConfig.java
@Configuration
@EnableAspectJAutoProxy
@ComponentScan
public class ConcertConfig {
}
CompactDisc.java
@Component
public class CompactDisc {
public void playTrack(int n) {
System.out.println("playTrack(" + n + ")");
}
}
TrackCounter.java
@Aspect
@Component
public class TrackCounter {
private Map<Integer, Integer> trackCounts = new HashMap<>();
@Pointcut("execution(* soundsystem.CompactDisc.playTrack(int)) && args(trackNumber)")
public void trackPlayed(int trackNumber){
}
@Before("trackPlayed(trackNumber)")
public void countTrack(int trackNumber) {
int currentCount = getPlayCount(trackNumber);
trackCounts.put(trackNumber, currentCount + 1);
for(Integer key : trackCounts.keySet())
System.out.println(key + ":" + trackCounts.get(key));
}
public int getPlayCount(int trackNumber) {
return trackCounts.containsKey(trackNumber) ? trackCounts.get(trackNumber) : 0;
}
}
測試
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ConcertConfig.class})
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CompactDiscTest {
@Autowired
private CompactDisc cd;
@Test
public void testPlayTrack() throws Exception {
cd.playTrack(20);
cd.playTrack(30);
cd.playTrack(60);
}
}
測試效果
20:1
playTrack(20)
20:1
30:1
playTrack(30)
20:1
60:1
30:1
playTrack(60)
Process finished with exit code 0