Defining pointcuts by pattern

Index

This post is part of an series of posts about AspectJ and AOP.

Pointcuts by pattern

Going through all the different ways of defining pointcuts and explaining them in an easy manner would be a near impossible feat for this post. Rather than aiming for the impossible let’s narrow down the scope, and talk about the most commonly used pointcut definitions and how we can experiment with them. We will get you started with defining your own pointcuts!

You can get the code for this blog series at the Git repository here.

Let’s start coding!

Requirements: Maven, Java 8, (preferably) an IDE (I’m using IntelliJ)

Patterns are designed by the following elements and any element in the pattern can use wildcards (*)

[modifiers] [return type] [(packageName)(className)(methodName)](parameters)

[modifiers] can be left blank; that will be interpreted as *

[void/object/primitive type] defined by either void , a specific object or a primitive type

[(packageName)(className)(methodName)] your.package.structure.ClassName.yourMethod  is valid. You can add * anywhere in that line to extend the search pattern

(parameters) yourMetod(..)  defines any method named yourMethod. The (..) is the parameter section. In this case it defines that it looks for none or any parameters.  If we replace the ..  with Integer  we will only look for a method called yourMethod(Integer)  and that has one parameter that is an Integer .

A real example:

 

In this example we are using the combinator  execution([pattern])  to define when this pointcut should be triggered. There are a whole list of different combinators at AspectJ’s homepage. Each one of them can take different patterns to help you define when your advice should be triggered.

JointPoint and ProceedingJointPoint

A JointPoint in the code is the call to the actual (method/object) in question. The ProceedingJointPoint  extends JointPoint to add the option to continue (proceed) the call to the (method/object) in question. The JointPoint contains a lot of information (such as parameters) that can be useful when writing the advice body.

Conclusion

Patterns can difficult – that’s why there are so many threads about how to define patterns online. Patterns gives us a lot of power, but demand that we know what we are looking for. Having the options to specify modifiers, return value and parameters gives us great tools to narrow down the complexity of our patterns.

You can get the code for this blog series at the Git repository here.

Index

This post is part of an series of posts about AspectJ and AOP.

Leave a Reply