以下介绍面向切面编程的两种主要方式:
一、使用execution定义pointcut方式
1、定义切面
@Aspect
@Component
public class LogIntercept {
@Pointcut(value="execution(public * com.example.demo..*.*(..))")
public void writeLog() {
}
@Before("writeLog()")
public void before() {
this.printLog("@Before 方法执行前——————做日志");
}
@Around("writeLog()")
public void around(ProceedingJoinPoint pjp) throws Throwable {
this.printLog("@Around 方法执行前——————做日志");
pjp.proceed();
this.printLog("@Around 方法执行后——————做日志");
}
@After("writeLog()")
public void after() {
this.printLog("@After 方法执行后——————做日志");
}
private void printLog(String str) {
System.out.println(str);
}
}
2、使用切面
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
return "hello";
}
}
二、使用注解定义pointcut方式
1、定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AroundTest {
String name() default "测试";
}
2、定义切面
@Component
@Aspect
public class AroundTestInteceptor {
public AroundTestInteceptor(){
}
@Pointcut(value="@annotation(com.example.demo.AroundTest)")
public void logAnnotatedMethod() {
}
@Around("logAnnotatedMethod()")
public void inteceptorAction(ProceedingJoinPoint pjp) throws Throwable {
Object o = null;
MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
Method method = joinPointObject.getMethod();
AroundTest annotation = method.getAnnotation(AroundTest.class);
Date enterDate = new Date();
System.out.println("开始执行方法:" + annotation.name());
o = pjp.proceed();
Date leaveDate = new Date();
System.out.println("结束执行方法:"+ annotation.name() +",方法执行的时间:" + (leaveDate.getTime() - enterDate.getTime()));
}
}
3、使用切面
@Component
public class PowerBoot implements ApplicationRunner {
private int i = 0;
@Override
@AroundTest
public void run(ApplicationArguments args) throws Exception {
System.out.println("自启动开启");
}
}
参考:
http://www.imooc.com/article/2670