利用Spring AOP 的原理实现函数运行计时的功能

最近要整理以前老员工写的代码,emmm,明明是前员工写的破代码,跑的慢,经历总说我的跑的慢,怎么办呢?

我一想干脆函数计时吧!我拿数据说话,哼

 

首先spring配置先拿上来




    
    

    
    



 

接下来,放测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring.xml"})
public class SpringTest {

    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void testAC() {
        SysAppService sysAppService = (SysAppService) applicationContext.getBean("sysAppService");
        List> allSysApp = sysAppService.getAllSysApp();
    }

}

我的切面类

 

package in.iask.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MethodTimeMonitor {

    private long startTime;

    //声明切面类路径,类型必须为final String类型的,注解里要使用的变量只能是静态常量类型的
    //public static final String POINT = "execution(* in.iask.service.*.*(..))";
    //也可以使用注解声明切入点,如下
    @Pointcut("execution(* in.iask.service.*.*(..))")
    public void point() {
    }

    @Before("point()")
    public void doBefore() {
        this.startTime = System.currentTimeMillis();
    }


    @After("point()")
    public void doAfter() {
        long endTime = System.currentTimeMillis();
        System.out.println("方法执行了" + (endTime - this.startTime) + "ms");
    }


    @Around("point()")
    public Object doAround(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();
        Object obj = null;
        try {
            obj = pjp.proceed();
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();

        MethodSignature signature = (MethodSignature) pjp.getSignature();
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
        System.out.println(methodName + "方法执行了" + (endTime - startTime) + "ms");
        return obj;
    }

}

执行结果


方法执行了1053ms

Process finished with exit code 0

 

你可能感兴趣的:(spring,aop)