Run advice on selected method using Advisor and Pointcut
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) { this.name = name; } public void getName() { System.out.println("Audi"); } public void drive(){ System.out.println("Driving"); } }
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 { @Override 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; import org.springframework.aop.support.StaticMethodMatcherPointcut; public class CarPointcut extends StaticMethodMatcherPointcut { @Override 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; import org.springframework.aop.support.DefaultPointcutAdvisor; 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(); pf.setTarget(carBean); pf.addAdvisor(advisor); // Get the proxied bean object Car carProxy=(Car)pf.getProxy(); carProxy.drive(); carProxy.getName(); } }
Output:
run:
Inside Before Method
Driving
Audi
BUILD SUCCESSFUL (total time: 1 second)