Java Reference
In-Depth Information
To introduce the
Counter
interface to all your calculator objects with
CounterImpl
as the
implementation, you can write the following introduction with a type-matching expression that
matches all the calculator implementations:
package com.apress.springenterpriserecipes.calculator;
...
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;
@Aspect
public class CalculatorIntroduction {
...
@DeclareParents(
value = "
com.apress.springenterpriserecipes.calculator.*CalculatorImpl",
defaultImpl =
CounterImpl.class)
public
Counter counter;
}
This introduction introduces
CounterImpl
to each of your calculator objects. However, it's still not
enough to keep track of the calling count. You have to increase the counter value each time a calculator
method is called. You can write an after advice for this purpose. Note that you must get the
this
object
but not the
target
object because only the proxy object implements the
Counter
interface.
package com.apress.springenterpriserecipes.calculator;
...
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class CalculatorIntroduction {
...
@After("execution(* com.apress.springenterpriserecipes.
➥
calculator.*Calculator.*(..))"
+ " && this(counter)")
public void increaseCount(Counter counter) {
counter.increase();
}
}
In the
Main
class, you can output the counter value for each of the calculator objects by casting them
into the
Counter
type.
package com.apress.springenterpriserecipes.calculator;
public class Main {
public static void main(String[] args) {
...
ArithmeticCalculator arithmeticCalculator =
(ArithmeticCalculator) context.getBean("arithmeticCalculator");
...
UnitCalculator unitCalculator =
Search WWH ::
Custom Search