import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LogInterceptor {
@Pointcut("execution(public * com.userService.*.add(..))") // 统配方式
public void mytime(){} //当多个同时使用同样的
long startTime,endTime;
@Before("mytime()")
public void before(){
startTime=System.nanoTime();
}
@After("mytime()")
public void after(){
endTime=System.nanoTime();
System.out.println("程序运行时间: "+(endTime-startTime)+"纳秒");
}
}
=======================================================================
使用XML 配置Aspect 可省略类中的注解
<!-- 声明类 ,此类作为切面类使用 -->
<bean id="logInterceptor" class="com.aop.LogInterceptor" />
<aop:config>
<!-- 设置切面名,及切面类 -->
<aop:aspect id="logAspect" ref="logInterceptor">
<!-- 运行前方法配置,先择要执行的方法 ,并设置切入点 -->
<aop:before method="before" pointcut="execution(public * com.userService.*.add(..))" />
<!-- 先设置切入点,待使用 -->
<aop:pointcut id="servicePointcut" expression="execution(public * com.userService.*.add(..))" />
<!-- 运行后方法配置,先择要执行的方法,参考预先设置好的切入点 -->
<aop:after method="after" pointcut-ref="servicePointcut" />
</aop:aspect>
</aop:config>
切面类 如下:
package com.aop;
public class LogInterceptor {
long startTime,endTime;
public void before(){
startTime=System.nanoTime();
}
public void after(){
endTime=System.nanoTime();
System.out.println("程序运行时间: "+(endTime-startTime)+"纳秒");
}
}
。