aop是spring的兩大功能模塊之一董饰,功能非常強大,為解耦提供了非常優(yōu)秀的解決方案霜第。
現在就以springboot中AOP的使用來了解一下AOP
導入對AOP的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
首先創(chuàng)建一個切面類,通過@Aspect來定義,為了使該類被正確被spring加載,必須增加@Component
@Aspect
@Component
public class LogAspect {
/**
* 定義需要切入的類或者方法
*/
@Pointcut("execution(public * com.zy.springboot.demo.controllers.*.*(..))")
public void webLog() {
System.out.println("web log executing");
}
/**
* 執(zhí)行切面類前執(zhí)行
*
* @param joinPoint
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
}
/**
* 執(zhí)行結束后
* @param joinPoint
*/
@After("webLog()")
public void doAfter(JoinPoint joinPoint) {
System.out.println("after web log");
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void afterReturning(Object ret) {
System.out.println(ret);
}
}
執(zhí)行順序:
after > before > afterReturning