Recipe 14.3. Defining an Aspect per Control FlowProblemYou want to declare that an aspect is to be instantiated on a per-control-flow basis. SolutionUse the percflow(Pointcut) aspect instantiation declaration. DiscussionThe percflow(Pointcut) statement indicates to the AspectJ compiler that it should create a new instance of the aspect for every new control flow that is entered within the set of join points indicated by the Pointcut parameter. Example 14-5 shows the percflow(Pointcut) instantiation declaration being used to specify a new instance of the PerControlFlow aspect for every new program control flow where the join points specified by the callPointCut( ) are encountered. Example 14-5. Using the percflow(Pointcut) to create a new instance of an aspect for every new program control flow enteredpublic aspect PerControlFlow percflow(callPointCut( )) { /* Specifies calling advice whenever a method matching the following rules gets called: Class Name: MyClass Method Name: foo Method Return Type: * (any return type) Method Parameters: an int followed by a String */ pointcut callPointCut( ) : call(void MyClass.foo(int, String)); // Advice declaration before( ) : callPointCut( ) && !within(PerControlFlow +) { System.out.println( "------------------- Aspect Advice Logic --------------------"); System.out.println( "In the advice attached to the call point cut"); System.out.println("Target: " + thisJoinPoint.getTarget( )); System.out.println("This: " + thisJoinPoint.getThis( )); System.out.println( "Aspect Instance: " + PerControlFlow.aspectOf( )); System.out.println( "------------------------------------------------------------"); } } Figure 14-4 shows how this relationship works in the case of the percflow(Pointcut) declaration. Figure 14-4. Creating a new aspect instance per program control flowThe percflow(Pointcut) statement represents the finest granularity of aspect instantiation policy and creates the largest number of distinct aspect instances for a particular piece of code. With this type of aspect instantiation declaration, the memory requirements of your aspects becomes more important. See AlsoThe call(Signature) pointcut is covered in Recipe Recipe 4.1; the within(TypePattern) pointcut is described in Recipe 7.1; the NOT(!) operator is described in Recipe 12.4. |