In this tutorial you will learn how to use JdkRegexpMethod in Spring aop pointcut to match the method by name in package.
In this tutorial you will learn how to use JdkRegexpMethod in Spring aop pointcut to match the method by name in package.In JdkRegexpMethodPointcut the most intertesting thing is its pattern matching method names spring matches fully qualified method name. This is a powerful concept which allows you to match all the method within a given package. The example given below illustrates the use of JdkRegexpMethodPointcut.
SimpleBean.java
package roseindia.net.bean; public class SimpleBean { public void sayHi() { System.out.println("Hi Friend"); } public void sayHi(String name) { System.out.println("Hi " + name); } public void greet() { System.out.println("Have a Nice Day......"); } }
SimpleAdvice.java
package roseindia.net.advice; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class SimpleAdvice implements MethodInterceptor { @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { System.out.println("Calling......" + methodInvocation.getMethod().getName()); Object object = methodInvocation.proceed(); System.out.println("End"); // TODO Auto-generated method stub return object; } }
MainClaz.java
package roseindia.net.main; import org.springframework.aop.Advisor; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.JdkRegexpMethodPointcut; import roseindia.net.advice.SimpleAdvice; import roseindia.net.bean.SimpleBean; public class MainClaz { public static void main(String[] args) { SimpleBean simpleBean = new SimpleBean(); JdkRegexpMethodPointcut jdkRegexpMethodPointcut = new JdkRegexpMethodPointcut(); jdkRegexpMethodPointcut.setPattern(".*sayHi.*"); SimpleAdvice advice = new SimpleAdvice(); Advisor advisor = new DefaultPointcutAdvisor(jdkRegexpMethodPointcut, advice); ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(simpleBean); proxyFactory.addAdvisor(advisor); SimpleBean proxy = (SimpleBean) proxyFactory.getProxy(); proxy.sayHi(); proxy.greet(); proxy.sayHi("Vinay"); } }When you run this application it will display message as shown below:
Calling......sayHi Hi Friend End Have a Nice Day...... Calling......sayHi Hi Vinay End |