Spring-Spring AOPNo Comments

In last Spring AOP advice examples, the entire methods of a class are intercepted automatically. But for most cases, you may just need a way to intercept only one or two methods, this is what ‘Pointcut’ come for. It allow you to intercept a method by it’s method name. In addition, a ‘Pointcut’ must be associated with an ‘Advisor’.

In Spring AOP, comes with three very technical terms – Advices, Pointcut , Advisor, put it in unofficial way…

  1. Advice – Indicate the action to take either before or after the method execution.
  2. Pointcut – Indicate which method should be intercept, by method name or regular expression pattern.
  3. Advisor – Group ‘Advice’ and ‘Pointcut’ into a single unit, and pass it to a proxy factory object.

Review last Spring AOP advice examples again.

CustomerService.java :

Spring-Customer.xml :


HijackAroundMethod.java : 

Run it


The entire methods of customer service class are intercepted. Later, we show you how to use “pointcuts” to intercept only


Pointcuts example

You can match the method via following two ways :

  1. Name match
  2. Regular repression match

1. Pointcuts – Name match example

Intercept a printName() method via ‘pointcut’ and ‘advisor’. Create a NameMatchMethodPointcut pointcut bean, and put the method name you want to intercept in the ‘mappedName‘ property value.

Create a DefaultPointcutAdvisor advisor bean, and associate both advice and pointcut.

Replace the proxy’s ‘interceptorNames’ to ‘customerAdvisor’ (it was ‘hijackAroundMethodBeanAdvice’).

Full bean configuration file

Run it again, output

Now, you only intercept the printName() method.

Spring comes with PointcutAdvisor class to save your work to declare advisor and pointcut into different beans, you can use NameMatchMethodPointcutAdvisor to combine both into a single bean.

2. Pointcut – Regular expression example

You can also match the method’s name by using regular expression pointcut – RegexpMethodPointcutAdvisor.

Now, it intercepts the method which has words ‘URL’ within the method name. In practice, you can use it to manage DAO layer, where you can declare “.*DAO.*” to intercept all your DAO classes to support transaction.





Be the first to post a comment.

Add a comment