美文网首页
aspectj实现AOP(基于log4j优化)

aspectj实现AOP(基于log4j优化)

作者: stutterr | 来源:发表于2017-07-31 23:17 被阅读15次

LogMethodTimeAspect类代码

其中doAround这个方法名字可以自己定义

package com.gavin.exam.advice;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import com.gavin.exam.service.impl.UserServiceImpl;

public class LogMethodTimeAspect {

    private final Logger logger = Logger.getLogger(UserServiceImpl.class);

    public void doAfter(JoinPoint jp) {
        System.out.println("log Ending method: " +
                jp.getTarget().getClass().getName() + "." +
                jp.getSignature().getName());
    }

    public Object doAround(ProceedingJoinPoint pjp) throws Throwable{

        long startTime = System.currentTimeMillis();

        Object returnValue = pjp.proceed();  //方法执行
        String methodName = pjp.getSignature().getName();
        long endTime = System.currentTimeMillis();

        StringBuilder sb = new StringBuilder();
        sb.append(pjp.getTarget().getClass().getSimpleName());
        sb.append(":");
        sb.append(methodName);
        sb.append(" time:");
        sb.append(endTime - startTime);
        logger.info(sb.toString());
        
        return pjp;
    }
}
···

###在`applicationContext`中定义bean
`<bean id="logMethodTimeAspect" class="com.gavin.exam.advice.LogMethodTimeAspect"></bean>`

###在`aop:config`中加入节点

    <aop:aspect id="logMethodTimeAspect" ref="logMethodTimeAspect">
        <aop:pointcut expression="execution(* com.gavin.exam.service..*.*(..))" id="businessService"/>
        <aop:before pointcut-ref="businessService" method="doBefore"/>
        <aop:around pointcut-ref="businessService" method="doAround"/>
        <aop:after-throwing pointcut-ref="businessService" method= "doThrowing" throwing="ex"/>
    </aop:aspect>

相关文章

网友评论

      本文标题:aspectj实现AOP(基于log4j优化)

      本文链接:https://www.haomeiwen.com/subject/ztldlxtx.html