Today we discuss about aspects precedence e.g. the order in which several aspects are processed at the same join point.
If you’re a heavy user of AspectJ you can sometimes end up with having more than one aspects for the same join point. In such case it could be interesting to know which aspect kicks in first and which one kicks in last. This order is called aspect precedence.
Without any specfic indication, the aspect ordering is totally unpredictable. It is not necessarily a problem if the aspects are totally unrelated.
I Aspects ordering
To declare aspect precedence, you can use the special keyword
declare precedence : <Type1Pattern>,<Type2Pattern>…<TypeNPattern>;
In the above example, aspect1has precedence over aspect2, which in turn has precedence over aspect3 etc. until aspectN.
By “has precedence over“, we mean “is executed before“. Generally the aspect with highest precedence executes first. The execution order also depends on the type of advice.
- the aspect with highest precedence kicks in before the lowest precedence aspect for around()/before() advice
- the aspect with highest precedence kicks in after the lowest precedence aspect for around()/after() advice
- the aspect with highest precedence wraps around the lowest precedence aspect for around() advice
Exemple:
declare precedence : around1, around2, before3, before4, after5;
One best practice in AspectJ is to declare a special aspect whose task consists simply of declaring precedence for other aspects.
public aspect MyAspectsOrdering { declare precedence : around1, around2, before3, before4, after5; declare precedence : Transactional*, around4; declare precedence : *, before2; }
It is possible to have many aspect precedence declarations in the same aspect but you should be very carefull not to introduce circular dependencies. It is perfectly possible to create a circular cycle of aspect precedence with several declarations and there will be no warning message from AspectJ.
Please notice that in the precedence declaration, you can also use wildcards *.
II Advices ordering
It is extremely rare though perfectly possible to have several advices applying to the same join point in one aspect:
public aspect MyAspect { pointcut myPointCut() : execution(* com.myApp..*(..)); Object around() : myPointCut() { // Around advice for myPointCut } before() : myPointCut() { // Before advice for myPointCut } }
In such cases, it is the lexical order e.g. the order in which the advices are declared in source code which applies.
The first picture under Aspects Ordering is wrong, because the after advice is always invoked after completing the around advices.
Good catch anythom! You’re right! I’m going to fix it in the picture.
Thank you for the useful comment
Okay great 🙂
By the way nice article! 😉
In XML should be this way:
Hm wordpress removed my custom tags. sorry