1. 程式人生 > 其它 >(五)5.1 SpringBoot 中使用Aop

(五)5.1 SpringBoot 中使用Aop

技術標籤:SpringBootSpring專案開發必知知識點

參考:https://my.oschina.net/u/3555122/blog/3170912


前言

在Spring中,不管是學習還是面試,有兩個點是永遠繞不過去的,一個是IOC,另一個就是Aop,Spring中使用Aop是非常簡單的,可以通過xml和註解兩種方式寫出aop的程式碼,那麼在SpringBoot中有什麼變化嗎?

在SpringBoot中使用aop實際上沒有太多的變化,關於SpringBoot實際上就是對Spring和SpringMVC的進一步封裝,因此在 SpringBoot 中同樣支援Spring框架中AOP切面程式設計,不過在SpringBoot中為了快速開發僅僅提供了註解方式的切面程式設計。

SpringBoot 註解式 aop 的使用

1.引入依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2.aop相關注解講解

/**
    @Aspect 用來類上,代表這個類是一個切面
    @Before 用在方法上代表這個方法是一個前置通知方法 
    @After 用在方法上代表這個方法是一個後置通知方法 
    @Around 用在方法上代表這個方法是一個環繞的方法
    @Around 用在方法上代表這個方法是一個環繞的方法
    @order(數字)用在類上,數字越小進入越早
**/
/**
    環繞,前置,後置全部存在
    先進入環繞,在進入前置,離開前置,離開環繞,進入後置,離開後置
**/

前置切面

/**
* @Aspect  用來類上,代表這個類是一個切面
* @Component 用來告訴SpringBoot 給當前類建立物件 等價於@Service
*/
@Aspect
@Component
public class MyAspect {
    //@Before 用在方法上代表這個方法是一個前置通知方法  註解的引數是切點表示式
    @Before("execution(* com.lu.service.*.*(..))")
    public void before(JoinPoint joinPoint){
        System.out.
println("前置通知"); //JoinPoint 通過該物件可以獲取到被切入的物件的資訊 joinPoint.getTarget();//目標物件 joinPoint.getSignature();//方法簽名 joinPoint.getArgs();//方法引數 } }

後置切面

@Aspect
@Component
public class MyAspect {
    @After("execution(* com.lu.service.*.*(..))")
    public void before(JoinPoint joinPoint){
        System.out.println("後置通知");
        joinPoint.getTarget();//目標物件
        joinPoint.getSignature();//方法簽名
        joinPoint.getArgs();//方法引數
    }
}

注意: 前置通知和後置通知都沒有返回值,方法引數都為joinpoint

環繞切面

@Aspect
@Component
public class MyAspect {
    @Around("execution(* com.lu.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

  • 如果不執行放行,不會執行目標方法
  • 一旦放行必須將目標方法的返回值返回,否則呼叫者無法接受返回資料

總結

以上就是SpringBoot中aop的簡單使用,以上實際上只是簡單的測試了aop的Api,關於aop的應用,例如:通過Aop記錄日誌資訊,通過Aop操作redis快取等實戰應用,。