SpringBoot實戰之AOP切面編程(五)

切面編程

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,如果執行放行,不會執行目標方法,一旦放行必須將目標方法的返回值返回,否則調用者無法接受返回數據

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章