AOP的应用(日志打印)

package com.ly.mp.iov.config;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LoggingAspect {

private static Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

/*
 *定义一个方法,用于声明切点表达式,该方法一般没有方法体
 *@Pointcut用来声明切点表达式
 *通知直接使用定义的方法名即可引入当前的切点表达式
 */
@Pointcut("execution(* com.ly.mp.iov.service.*.*(..))")
public void pointcutDeclaration() {}

//前置通知,方法执行之前执行
@Before("pointcutDeclaration()")
public void beforeMethod(JoinPoint jp) {
    String targetClassName = jp.getTarget().getClass().getName();
    String methodName = jp.getSignature().getName();
    Object[] args = jp.getArgs();
    String param = null;
    if( jp.getArgs() != null  ) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append( "[" );
        for( Object arg : jp.getArgs() )
        {
            if( stringBuffer.toString().length() > 1 ) {
                stringBuffer.append( "," );
            }
            try {
                stringBuffer.append( JSON.toJSONString( arg ) );
            }catch (Exception e) {
                stringBuffer.append( "unSupportType" );
            }

        }
        stringBuffer.append( "]" );
        param = stringBuffer.toString();
    }
    logger.info( "{}.{} receive data:{}" , targetClassName , methodName , param );
}

//后置通知,方法执行之后执行(不管是否发生异常)

// @After(“pointcutDeclaration()”)
// public void AfterMethod(JoinPoint jp) {
// String methodName = jp.getSignature().getName();
// Object[] args = jp.getArgs();
// System.out.println("AfterMethod The method “+ methodName +” parameter is "+Arrays.asList(args));
// System.out.println();
// }

//返回通知,方法正常执行完毕之后执行
@AfterReturning(value="pointcutDeclaration()",returning="result")
public void afterReturningMethod(JoinPoint jp , Object result) {
    String targetClassName = jp.getTarget().getClass().getName();
    String methodName = jp.getSignature().getName();
    logger.info( "{}.{} return data:{}" , targetClassName , methodName , JSON.toJSONString( result ) );
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值