Aspect with Parameters



import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class TrackGame {
    private Map<Integer, Integer> gameCounts = new HashMap<Integer, Integer>();
   
    @Pointcut("execution(* game.Football.playGame(int)) && args(gameNumber)")
    public void countGame(int gameNumber) {}
   
    @Before("countGame(gameNumber)")
    public void gamePlayed(int gameNumber) {
        int currentCount = getGamePlayCount(trackNumber);
        gameCounts.put(trackNumber, currentCount + 1);
    }
   
    public int getGamePlayCount(int gameNumber) {
        return gameCounts.containsKey(gameNumber) ? gameCounts.get(gameNumber) : 0;
    }
}


Here: @Pointcut("execution(* game.football.playGame(int)) && args(gameNumber)")

1) Above line defines a named pointcut with its name :countGame(gameNumber)
2) In @Pointcut declation * indicates any return type
3) args(gameNumber) defines the name of the Argument
4) This "game.football.playGame(int)" is the method with int argument.
   That int argument will be mapped with the gameNumber in args(gameNumber)
5) This "countGame(gameNumber)" we can use it in @Before @After with any method.

Test It

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=TrackCounterConfig.class)
public class TrackFootbalGameTest {
    @Rule
    public final StandardOutputStreamLog log = new StandardOutputStreamLog();
   
    @Autowired
    private Football footbal;
   
    @Autowired
    private TrackGame trackGame;
   
    @Test
    public void testTrackGame() {
        footbal.playGame(1);
        footbal.playGame(2);
        footbal.playGame(4);
        footbal.playGame(1);
        footbal.playGame(10);
       
        assertEquals(1, counter.getPlayCount(18));
    }
}