AspectJ spring aop 记录某些类中方法执行时间实例

来源:互联网 发布:mac上的app怎么卸载 编辑:程序博客网 时间:2024/06/05 08:13

最近在系统上线完之后发现有些模块效率不高,耗时较长,所以打算记录一下某块代码的执行时间,可以自己手工每个方法去加,但是那样就破坏了原因的代码,何况还有些代码不是一个人写的,这样就增加了代码的侵入性(引自spring) google了一下发现网上已经有大把的这种例子,发现用spring的apo可以完美的解决该问题

 

现在要求如下:

要将service业务层的方法都记录下来方法执行时间,

所要引入的包括三部分:

1 log日志部分,目前,系统里面的日志用的log4j

2 aop切面记录工具类

3 spring配置文件

 

第一 log4j的配置就不需要在此唠叨,如果不清楚可以直接百度,此处只是用一下记录日志

第二aop切面工具类 MethodTimeAdvice 该类继承了spring aop的一个org.aopalliance.intercept.MethodInterceptor 类,继而可以获取切点进行通知

工具类如下,仅仅是为了演示,代码仅供参考

 

package com.p95169.hrs.common.utils;import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;import org.apache.commons.lang.StringUtils;import org.apache.commons.lang.time.StopWatch;import org.apache.log4j.Logger;/** * 记录方法的执行时间 * @author Unmi */public class MethodTimeAdvice implements MethodInterceptor {  public static Logger logger=Logger.getLogger(MethodTimeAdvice.class);    /**     * 拦截要执行的目标方法     */    public Object invoke(MethodInvocation invocation) throws Throwable {    //用 commons-lang 提供的 StopWatch 计时,Spring 也提供了一个 StopWatch    StopWatch clock = new StopWatch();        clock.start(); //计时开始        Object result = invocation.proceed();        clock.stop();  //计时结束    //方法参数类型,转换成简单类型    Class[] params = invocation.getMethod().getParameterTypes();    String[] simpleParams = new String[params.length];    for (int i = 0; i < params.length; i++) {simpleParams[i] = params[i].getSimpleName();}    logger.info("该方法执行耗费:" + clock.getTime() + " ms ["                + invocation.getThis().getClass().getName() + "."                + invocation.getMethod().getName() + "("+StringUtils.join(simpleParams,",")+")] ");        return result;    }}


第三 切点和通知的配置(spring的applicationContext.xml文件)

 

<!-- 日志记录某个类中方法花费时间aop --><aop:config>        <!-- Spring 2.0 可以用 AspectJ 的语法定义 Pointcut,这里拦截 service 包中的所有方法 -->        <aop:advisor id="methodTimeLog" advice-ref="methodTimeAdvice" pointcut="execution(* com.p95169.hrs..*Mgr*.*(..))"/>    </aop:config>    <bean id="methodTimeAdvice" class="com.p95169.hrs.common.utils.MethodTimeAdvice"/>

原创粉丝点击