A pointcut is a predicate that matches the join points and a pointcut expression language is a way of describing pointcuts programmatically.
A joinpoint is a point in program execution where you can add additional behavior. Spring applications only support method based joinpoints.
Pointcut Designators:A pointcut expression starts with a pointcut designator (PCD), which is a keyword telling Spring AOP what to match. There are several pointcut designators, such as the execution of a method, a type, method arguments, or annotations.
execution:The primary Spring PCD is execution, which matches method execution join points. Let us look into some examples:
- execution(* com.spring.example.bean.aop.TestClass.*(..)) : This advice will be applied to all the methods of TestClass.
- execution(* TestClass.*(..)): You can omit the package if the TestClass and the advice is in the same package.
- execution(public * TestClass.*(..)): This advice will be applied to the public methods of TestClass.
- execution(public int TestClass.*(..)): This advice will be applied to the public methods of TestClass and returning an int.
- execution(public int TestClass.*(int, ..)): This advice will be applied to the public methods of TestClass and returning an int and having first parameter as int.
- execution(public int TestClass.*(int, int)): This advice will be applied to the public methods of TestClass and returning an int and having both parameters as int.
within:Another way to achieve the same result from the previous section is by using the within PCD, which limits matching to join points of certain types.
Let us look into some examples.
- within(com.spring.example.bean.aop.*) : This will match all the methods in all classes of com.spring.example.bean.aop.
- within(com.spring.example.bean.aop..*) : This will match all the methods in all classes of com.spring.example.bean.aop and its sub packages. The only difference is the extra dot(.) after package.
- within(com.spring.example.bean.aop.TestClass) : This will match all the methods in the TestClass.
- within(TestClass) : Again, if the target class is located in the same package as this aspect, the package name can be omitted.
- within(TestInterface+) : This will match all the methods which are in classes which implement TestInterface.
Bean Name Patterns
You can match all beans as well having a common naming pattern. For example, the following pointcut expression matches beans whose name ends with Service.
bean(*Service)
Combining Pointcut Expressions
Pointcut expressions can be combined using && (and), ||(or), and !(not).
For example,
within(TestInterface1+)/||/within(TestInterface2+)
The above patterns will match all join point in all classes which implement TestInterface1 or TestInterface2