利用aop拦截注解获取方法的运行时间

一直对aop的理解不是很深,前天有个需求 就是要获得多个方法的运行时间总不能每个方法的运行前后都加上时间吧 这个时候aop就很方便了 刚开始的时候用的切入点 弄完以后发现一个问题,切入点用着很不方便。假如我想看看另个包中的方法运行时间,是不是就要重新配置下切入点。而且我只想知道一个类中某个方法的运行时间其他的方法我不想获取到,显然用切入点比较局限。我在网上爬了些资料改进成用注解实现aop。废话不多说上代码。

1. 自定义一个注解类

 1 /**
 2  * 用来获得方法执行时间的注解
 3  */
 4 @Target({ElementType.METHOD})
 5 @Retention(RetentionPolicy.RUNTIME)
 6 @Documented
 7 @Inherited
 8 public @interface  RunTime {
 9 
10 }

2.定义一个aop切面(我这里有两种实现方式    (1)Around用的是我自定义需要拦截的注解。(2)BeforeAfter用的是切入点)

@Aspect
@Component
public class MethodTimeMonitor {
    private long startTime;

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

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

    @After("point()")
    public void doAfter() {
        //接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        long endTime = System.currentTimeMillis();
        System.out.println(request.getMethod()+"方法执行了" +(endTime - this.startTime) + "ms");
    }
    @Around("@annotation(runTime)")
    public Object doAround(ProceedingJoinPoint pjp, RunTime runTime){
        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;
    }

3.自定义注解的使用(我们想知道哪个方法的运行时间 只需要在这个方法上面加上我们自定义注解@RunTime就可以了)

 1 /**
 2      * 后台菜单页面分页查询
 3      * @param page
 4      * @param limit
 5      * @param menu_name
 6      * @return
 7      */
 8     @RequestMapping("getAllMenu")
 9     @ResponseBody
10     @RunTime
11     public ResultMap getAllMenu(@RequestParam Integer page, @RequestParam Integer limit, @RequestParam(required = false) String menu_name) {
12         ResultMap<List<Menu>> resultMap = new ResultMap<>();
13         Page<Menu> pageInfo = new Page<>(page, limit);
14         Wrapper<Menu> wrapper = new EntityWrapper<>();
15         wrapper = menu_name == null ? wrapper : wrapper.like("menu_name", menu_name);
16         List<Menu> menuList = dao.selectPage(pageInfo, wrapper.orderBy("id", false)).getRecords();
17         resultMap.setData(menuList);
18         resultMap.setCount(dao.selectCount(wrapper));
19         return resultMap;
20     }

猜你喜欢

转载自www.cnblogs.com/liyongsheng/p/10668759.html