O'Reilly logo

AspectJ Cookbook by Russ Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.2. Defining an Aspect per Instance

Problem

You want to declare that an aspect is to be instantiated on a per-object-instance basis.

Solution

Use the perthis(Pointcut) or pertarget(Pointcut) aspect instantiation policy declarations.

Discussion

AspectJ provides the perthis(Pointcut) and pertarget(Pointcut) aspect instantiation policies to declare an aspect should be instantiated for every new object instance according to the classes selected with the Pointcut definition.

The difference between the perthis(Pointcut) and the pertarget(Pointcut) declarations has to do with what object is examined when an advised join point is reached. The perthis(Pointcut) declaration specifies that a new aspect will be instantiated for every new object referenced by this at the advice triggering join point. The pertarget(Pointcut) instantiation policy specifies that a new aspect will be instantiated for every new object that is the target of an advice triggering join point. Despite these subtle differences, both declarations explicitly associate a single aspect instance to a single object instance.

Example 14-2 shows how a perthis(Pointcut) declaration can be assigned to a particular aspect, and Figure 14-2 shows how the aspect instantiation policy is realized within the flow of an application.

Example 14-2. Using the perthis(Pointcut) declaration to instantiate an aspect for every executing object

public aspect PerThis perthis(callPointCut( )) { /* Specifies calling advice whenever a method matching ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required