Spring AOP 之 RegexpMethodPointcutAdvisor
昨天,做了有关日志的AOP,对相关的AOP知识总结如下:
1.引入AOP(Aspect Oroented Programming) 面向切面编程,是消除代码重复的一种方法。
2.Spring AOP 中提供了两种PointcutAdvisor,分别是:
①org.springframework.aop.support.RegexpMethodPointcutAdvisor (需要加上完整类名,可以用Spring提供的匹配方式)
②org.springframework.aop.support.NameMatchMethodPointcutAdvisor(只需要方法名,不用加类名)
今天,主要来说明下RegexpMethodPointcutAdvisor的用法。贴一个例子来说明,一些说明都写在注释中~看贴的代码:
1 2 3 4 5 6 7 8 9 | /** * 打印接口 * @author ChenST */ public interface IPrinter { /** 打印接口 */ public void print(); } |
1 2 3 4 5 6 7 8 9 10 11 12 | /** * 打印接口实现类 * @author ChenST */ @Repository public class PrinterImpl implements IPrinter{ @Override public void print() { System.out.println( "hello world" ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /** * 通知,在执行方法执行后调用该方法 * @author ChenST */ //对应的还有MethodBeforeAdvice等 public class AfterPrinter implements AfterReturningAdvice{ //第一个参数表示 切入方法的 [返回对象] //第二个参数表示 切入方法的 [方法反射对象] //第三个参数表示 切入方法的 [参数数组(方法的所有参数组成)] //第四个参数表示 [调用该方法的对象] @Override public void afterReturning(Object returnObject, Method method, Object[] argArray, Object callObject) throws Throwable { System.out.println( "add log:print Hello world" ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | < context:annotation-config /> < context:component-scan base-package = "com.shine" /> < bean id = "printer" class = "com.shine.PrinterImpl" /> < bean id = "afterPrinter" class = "com.shine.AfterPrinter" /> <!-- 配置一个拦截器 (切入点对象,确定何时何地调用拦截器) --> < bean id = "pointcutAdvisor" class = "org.springframework.aop.support.RegexpMethodPointcutAdvisor" > <!-- [通知,特定连接点所采取的动作] --> <!-- 加入切面,切面为当执行完print方法后 再执行加入的切面 --> < property name = "advice" > < ref local = "afterPrinter" /> </ property > <!-- 要拦截的方法,可根据Spring提供匹配方式进行拦截 --> < property name = "pattern" > <!-- .表示符合任何单一字元 ### +表示符合前一个字元一次或多次 ### *表示符合前一个字元零次或多次 ### \Escape任何Regular expression使用到的符号 --> <!-- .*表示前面的前缀(包括包名) 表示print方法--> < value >.*print</ value > </ property > </ bean > <!-- ### 代理工程 --> < bean id = "proxyFactory" class = "org.springframework.aop.framework.ProxyFactoryBean" > <!-- 指定目标对象,目标对象是PrinterImpl对象 --> < property name = "target" > < ref local = "printer" /> </ property > <!-- 该目标中加入拦截器pointcutAdvisor --> < property name = "interceptorNames" > < list > < value >pointcutAdvisor</ value > </ list > </ property > </ bean > |
1 2 3 4 5 6 7 8 9 10 11 12 13 | /** * 测试类 */ public class TestMain { public static void main(String[] args) { ApplicationContext ctx = new FileSystemXmlApplicationContext( "classpath:applicationContext.xml" ); // ☆注意:这里的Bean对象获取必须从代理工厂中去取,否则无法切入 IPrinter printer = (IPrinter) ctx.getBean( "proxyFactory" ); printer.print(); } } |
1 2 | hello world add log : print Hello world |
感觉这么多开源东西中,最需要研究的就是Spring了~~ = =|| 继续study~~