Run advice on selected method using Advisor and Pointcut

Last Updated: February 20, 2018

This is the Car bean class which we are going to use in this example. We have two methods drive() and getName() in this class. I need to run advice when drive() method is called. I do not need to run the advice on getName() method is called

We can do this using pointcut mechanism

package com.kayak;
import org.springframework.stereotype.Component;

public class Car  {
    private String name;

    public void setName(String name) { = name;
    public void getName() {
    public void drive(){

Next, you can create the CarAvice class which implements the interface MethodBeforeAdvice and you have the method name before() which will be called before the drive() of the Car

package com.kayak;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class CarAdvice implements MethodBeforeAdvice {

    public void before(Method method, Object[] os, Object o) throws Throwable {
       System.out.println("Inside Before Method");

So,next I will create the Pointcut. CarPointcut class extends the StaticMethodMatcherPointcut and you can override the match method and check the method name with drive and return the boolen result

package com.kayak;

import java.lang.reflect.Method;

public class CarPointcut extends StaticMethodMatcherPointcut {

    public boolean matches(Method method, Class<?> type) {
       return ("drive".equals(method.getName()));

Now you can run the following code to test your code. First you carte the target object and Pointcut object. You create the Advisor object with the DefaultPointcutAdvisor by passing constrctor argumets pointcut and advice objects. Then you create the ProxyFactory object and set the target object and add the advisor object

Finalyy you get the proxy object and call the methods

When you look at the output you can observer that Advice will be run only when you call the drive(). That is why you can see the “Inside Before Method” text in your console before the text “drive”

package com.kayak;
import org.springframework.aop.Advisor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;

public class Test {
    public static void main(String[] args) {
          Car carBean= new Car();
          Pointcut pointcut= new CarPointcut();
          CarAdvice cd= new CarAdvice();
          Advisor advisor= new DefaultPointcutAdvisor(pointcut,cd );
          ProxyFactory pf=new ProxyFactory();
          // Get the proxied bean object
          Car carProxy=(Car)pf.getProxy();


Inside Before Method
BUILD SUCCESSFUL (total time: 1 second)