1. 服务类功能代码
package com.demo.service;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements HelloInterface {
public void sayHello() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("userHello");
}
}
目标类需要在Spring Context管理。
2. 切面类
package com.demo.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Service;
@Service
@Aspect
public class TimeMonitor {
@Around("execution(* com.demo.service.UserServiceImpl.sayHello(..))")
public void monitorAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("method start time:" + System.currentTimeMillis());
Object re = pjp.proceed();
System.out.println("method end time:" + System.currentTimeMillis());
}
}
- 切面类有两个注释,分别是@Service和@Aspect,第一个注解是使得TimeMonitor类受Spring托管并实例化。@Aspect就是使得这个类具有AOP功能两个注解缺一不可。
- 类里面只有一个方法,名字叫做monitorAroud,其实就是为了检测函数执行时间的!
- @Around表示使用的是环切,执行方法调用前,执行该切面方法,通过pjp.proceed();调用目标方法,目标方法执行完成后,继续执行后续方法。完整的处理,还可以增加异常处理。
3. 切面依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
4. 调用方法可以获得目标方法的执行时间
method start time:1480223298250
method end time:1480223299250
通过切面,可以方便地对方法执行时间、调用日志、异常处理等进行统一处理。