spring的AOP学习[5]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:

<property name="proxyInterfaces">

      <value>com.softbrain.wangzl.business.ITest</value>

</property>

这里用到了Interfaces,接口在java程序中的优点在这就不赘述,如果使用接口,spring容器会使用动态代理,如果不使用接口,可以在这里将上面那句话换成

<property name="proxyTargetClass">

      <value>true</value>

</property>

这样容器会使用CGLIB代理,CGLIB和动态代理在性能上有微小的区别,对Spring 1.0来说,后者稍快。

interceptorNames在spring的源码中是一个private String[] interceptorNames;

这说明可以配置多个interceptor,这里只用了一个.

ProxyFactoryBean的具体配置可以参考spring的源码

 3.     <bean id="MyInterceptor"

              class="com.softbrain.wangzl.business.MethodTimeCostInterceptor"/>

              class="com.softbrain.wangzl.business.MethodTimeCostInterceptor"/>

这是AOP的Interceptor类,代码如下

public class MethodTimeCostInterceptor implements MethodInterceptor, Serializable{
    static Logger log = null;
 /* (non-Javadoc)
  * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
  */
 public Object invoke(MethodInvocation invocation) throws Throwable {
     log = Logger.getLogger(invocation.getMethod().getName());
  
  long time = System.currentTimeMillis();
  log.info("begin");
  Object rval = invocation.proceed();
  
  System.out.println(invocation.getMethod().getParameterTypes());
  time = System.currentTimeMillis() - time;
  log.info("end");
  System.out.println(time);
  
  return rval;
 }
}

 这里捕获所有的ITest接口的方法,计算运行时间并打印log

 这里捕获所有的ITest接口的方法,计算运行时间并打印log

接口的方法,计算运行时间并打印log

这里问题来了,能否像spring的事务处理那样对指定的方法使用AOP哪?

可以,

 

 <bean id="settersAndAbsquatulateAdvisor"
    class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
    <property name="advice">
        <ref local="MyInterceptor"/>
    </property>
    <property name="patterns">
        <list>
            <value>select*</value>
        </list>
    </property>
</bean>

本文关键:spring的AOP学习
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top