监视服务提供者中ServiceImpl中方法的调用

来源:互联网 发布:淘宝靠谱的美妆卖家 编辑:程序博客网 时间:2024/05/21 18:53

监视服务提供者中方法的调用情况,统计方法执行所需要的时间

_**使用到了slf4jFactory提供给的类
-**使用到了aspectj的连接点和环绕通知和切面
_**可以在服务调用者中使用,监视服务对服务提供者的调用情况

1、导入pom文件中导入maven依赖

  <dependency>            <groupId>org.aspectj</groupId>            <artifactId>aspectjweaver</artifactId>            <version>1.7.4</version>        </dependency>

2、新增实体类

package cn.org.demo;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.lang.reflect.Proxy;@Aspectpublic class ServiceMonitor {    private static final Logger logger = LoggerFactory.getLogger(ServiceMonitor.class);    @Around("execution(* cn.org..*Service.*(..))|| execution(* cn.org..*Interface.*(..))")    public Object serviceInfo(ProceedingJoinPoint joinPoint) {        Object target = joinPoint.getTarget();        String className = null;        String methodName = joinPoint.getSignature().getName();        if ((Proxy.isProxyClass(target.getClass()))) {            className = target.toString();       }else {            className=target.getClass().getName();        }        long begin = System.currentTimeMillis();        try {           Object retVal=  joinPoint.proceed();           return retVal;        } catch (Throwable throwable) {            throwable.printStackTrace();            throw new RuntimeException("方法执行异常!",throwable);        }finally {            long costTime = System.currentTimeMillis() - begin;            logger.error("className:{} methodName:{} costtime:{}", className, methodName, costTime);        }    }}

3、在在contextConfigLocation定义的配置文件中引入对aspectj aop的支持

<aop:aspectj-autoproxy proxy-target-class="true" />

3、在同样的配置文件中定义该对象,使该对象成为一个父容器中的对象,如果定义在子容器SpringMVC配置文件中会出错

<bean id="serviceMonitor" class="该类全路径名" />
阅读全文
0 0
原创粉丝点击