Project(20)——Spring AOP - 统计业务方法的执行时间
统计业务方法的执行时间
AOP指的是“面向切面的编程”。
AOP并不是Spring框架的特征,只不过Spring提供了很好的支持,使得AOP更易于实现。
在使用Spring AOP之前,需要添加AOP相关的依赖:
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.4</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.5.3</version>
<type>pom</type>
</dependency>
接下来,创建cn.tedu.store.aop.TimeElapsedAspect
切面类,该切面类的对象将由Spring框架管理,所以,必须在cn.tedu.store
包下,且需要添加@Component
和@Aspect
注解:
@Component
@Aspect
public class TimeElapsedAspect{
}
然后,在类中添加切面方法,关于切面方法:
- 应该使用
public
权限; - 可以使用
void
作为返回值类型,如果是@Around
必须使用Object
作为返回值类型; - 方法名称可以自由定义;
- 参数根据切面的作用范围来决定,例如使用
@Around
时必须添加ProceedingJoinPoint
参数。
所以,在切面类中添加切面方法︰
public void process(ProceedingJoinPoint pjp) throws Throwable{
// 记录起始时间
long start = System.currentTimeMillis();
// 执行任务
pjp.proceed();
// 记录结束时间
long end = System.currentTimeMillis();
// 统计耗时
System.err.println("耗时:" + (end - start) + "ms.");
}
最后,还应该确定该切面方法的作用范围,即何时、哪些处理流程中,需要应用这个切面!
根据作用范围,可以使用@Before
,@After
,或使用@Around
表示在应用的方法之前和之后都需要执行某些任务。
然后,还需要在@Around
注解中配置参数,以决定切面应用于哪里:
至此,对于应用范围之内所有返回值类型为void
的业务方法都可以正常应用切面,如果需要保证其它业务方法也能正常运行,则需要获取方法执行时的返回值,
并且,整个切面方法也需要将返回值类型设置为0bject
,并在方法运行结束之前返回以上结果:
使用@Before
表示切面将存于某位置之前,使用@After
表示切面将存在于某位置之后,通常,使用@Around
可以完全取代@Before
或@After
!