切面程式設計
1 引言
springboot是對原有項目中spring架構和springmvc的進一步封裝,是以在springboot中同樣支援spring架構中AOP切面程式設計,不過在springboot中為了快速開發僅僅提供了注解方式的切面程式設計.
2 使用
2.1 引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.2 相關注解
@Aspect 用來類上,代表這個類是一個切面
@Before 用在方法上代表這個方法是一個前置通知方法
@After 用在方法上代表這個方法是一個後置通知方法 @Around 用在方法上代表這個方法是一個環繞的方法
@Around 用在方法上代表這個方法是一個環繞的方法
2.3 前置切面
@Aspect
@Component
public class MyAspect {
@Before("execution(* com.baizhi.service.*.*(..))")
public void before(JoinPoint joinPoint){
System.out.println("前置通知");
joinPoint.getTarget();//目标對象
joinPoint.getSignature();//方法簽名
joinPoint.getArgs();//方法參數
}
}
2.4 後置切面
@Aspect
@Component
public class MyAspect {
@After("execution(* com.baizhi.service.*.*(..))")
public void before(JoinPoint joinPoint){
System.out.println("後置通知");
joinPoint.getTarget();//目标對象
joinPoint.getSignature();//方法簽名
joinPoint.getArgs();//方法參數
}
}
> 注意: 前置通知和後置通知都沒有傳回值,方法參數都為joinpoint
2.5 環繞切面
@Aspect
@Component
public class MyAspect {
@Around("execution(* com.baizhi.service.*.*(..))")
public Object before(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("進入環繞通知");
proceedingJoinPoint.getTarget();//目标對象
proceedingJoinPoint.getSignature();//方法簽名
proceedingJoinPoint.getArgs();//方法參數
Object proceed = proceedingJoinPoint.proceed();//放行執行目标方法
System.out.println("目标方法執行之後回到環繞通知");
return proceed;//傳回目标方法傳回值
}
}
注意: 環繞通知存在傳回值,參數為ProceedingJoinPoint,如果執行放行,不會執行目标方法,一旦放行必須将目标方法的傳回值傳回,否則調用者無法接受傳回資料