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

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

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

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”


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