目录
- 文件目录
- 切点表达式
- 源码
- 测试
- 测试效果
文件目录
soundsystem
|- ConcertConfig
|- CompackDisc
|- TrackCounter
切点表达式
返回任意类型 方法所属的类型 方法 接受int类型的参数
|-||---------------------| |-------||---|
execution(* soundsystem.CompactDisc.playTrack(int)) && args(trackNumber)
|---------------|
指定参数
源码
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
网友评论