spring配置文件中的配置:
<!--指向一个javaBean-->
<bean class="com.tg.common.core.util.AOPService" />
<!--开启注解-->
<aop:aspectj-autoproxy />
类中的代码:
package com.tg.common.core.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AOPService {
private Long startTime;
private Long endTime;
private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
//方法调用前
@Before("execution(* com.tg.attendance.service..*.*(..))")
public void startMethod(JoinPoint jp){
Date date=new Date();
String className = jp.getThis().toString();
//获得方法名
String methodName = jp.getSignature().getName();
System. out.println("=====================================" );
System. out.println(sdf.format(date)+" 调用" +className+"类中"+methodName+"方法-开始!");
startTime=date.getTime();
//获得参数列表
Object[] args = jp.getArgs();
if(args.length <=0){
System. out.println("此方法没有参数");
} else{
for(int i=0; i<args.length; i++){
System. out.println("此方法参数为:"+(i+1)+":"+args[i]);
}
}
System. out.println("=====================================" );
}
//方法调用后
@After("execution(* com.tg.attendance.service..*.*(..))")
public void endMethod(JoinPoint jp){
Date date=new Date();
String className = jp.getThis().toString();
//获得方法名
String methodName = jp.getSignature().getName();
System. out.println("=====================================" );
System. out.println(sdf.format(date)+" 调用" +className+"类中"+methodName+"方法-结束!");
endTime=date.getTime();
System.out.println("调用此方法共消耗:"+(endTime-startTime)+"毫秒");
System. out.println("=====================================" );
}
}
说明:
execution(* com.tg.attendance.service..*.*(..)) service包下的所有类中的所有方法