LogPointcut.java中内容如下:
package com.demo.aop.log;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class LogPointcut {
@Pointcut("execution(* com.demo.service..*.*(..))" )
public void inServiceLayer() { }
}
解释:
加上@Aspect注解
@Pointcut是切入点,指定需要注入代码的位置,如上面代码中指定在com.demo.service包下的所有类的所有方法中
下面只需要定义一个方法签名
LogAdvice.java中的内容如下:
package com.demo.aop.log;
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 LogAdvice {
/**
* 在方法开始前纪录
* @param jp
*/
@Before("com.demo.aop.log.LogPointcut.inServiceLayer()" )
public void logInfo(JoinPoint jp) {
String className = jp.getThis().toString();
String methodName = jp.getSignature().getName(); //获得方法名
System. out.println("=====================================" );
System. out.println("====位于:" +className);
System. out.println("====调用" +methodName+"方法-开始!");
Object[] args = jp.getArgs(); //获得参数列表
if(args.length <=0){
System. out.println("====" +methodName+"方法没有参数");
} else{
for(int i=0; i<args.length; i++){
System. out.println("====参数 " +(i+1)+":"+args[i]);
}
}
System. out.println("=====================================" );
}
/**
* 在方法结束后纪录
* @param jp
*/
@After("com.demo.aop.log.LogPointcut.inServiceLayer()" )
public void logInfoAfter(JoinPoint jp) {
System. out.println("=====================================" );
System. out.println("====" +jp.getSignature().getName()+"方法-结束!");
System. out.println("=====================================" );
}
}
解释:
@Before 使用Pointcut中的方法签名找到切入点
记录并打印日志
application.xml配置文件中加入如下配置:
<aop:aspectj-autoproxy />
<bean class="com.demo.aop.log.LogAspect" />
|
|