Java Spring Boot AOP

在 Spring Boot 2.7.14 版本中,你可以使用 Java 配置類的方式來實現在 Spring Boot 應用程序中添加 AOP 的效果,替代 XML 配置。在 Java 配置類中,你需要完成以下步驟:

1. 創建一個 Aspect 類,其中包含需要植入的橫切關注點(cross-cutting concerns)邏輯。
2. 創建一個配置類,用於啟用 AspectJ 自動代理支持。

以下是具體的步驟:

Step 1: 創建 Aspect 類
```java
package com.example.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {
    
    @Before("execution(* com.example.controller.*.*(..))")
    public void beforeControllerMethods() {
        // 在這裡編寫在目標方法執行前執行的邏輯
        System.out.println("Before executing controller methods...");
    }
}
```

上述代碼中,我們創建了一個名為 `MyAspect` 的 Aspect 類,它通過 `@Aspect` 註解標記為一個 Aspect,並使用 `@Component` 註解使其成為 Spring 託管的組件。在 `beforeControllerMethods` 方法中,我們使用 `@Before` 註解定義了一個切入點,該切入點將在 `com.example.controller` 包中所有方法執行前執行,你可以根據自己的需求修改切入點表達式。

Step 2: 創建配置類
```java
package com.example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.example.aspect")
public class AppConfig {
    // 這裡不需要寫其他配置,只需使用@EnableAspectJAutoProxy啟用AspectJ自動代理
}
```

在上述配置類中,我們使用了 `@Configuration` 註解標記它為一個配置類,並通過 `@EnableAspectJAutoProxy` 註解啟用 AspectJ 自動代理支持。 `@ComponentScan` 註解用於掃描 `com.example.aspect` 包中的 Aspect 類。

Step 3: 確保主應用程序類中添加了 `@SpringBootApplication` 註解
```java
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;

import com.example.config.AppConfig;

@SpringBootApplication
@Import(AppConfig.class)
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}
```

在主應用程序類(通常名為 `YourApplication` 或類似的名稱)中,你需要確保添加了 `@SpringBootApplication` 註解,同時使用 `@Import` 註解將上面創建的配置類 `AppConfig` 引入。

這樣,你就在 Spring Boot 應用程序中實現了與你提供的 `spring-mvc-crud-demo-servlet.xml` 中 `<aop:aspectj-autoproxy/>` 相同的 AOP 效果。在運行應用程序時,每當 `com.example.controller` 包中的方法被調用時,Aspect 類 `MyAspect` 中定義的邏輯將被自動執行。

Comments

Popular posts from this blog

How to use Visual Studio Code to debug ReactJS application

Github Link & Web application demonstration on YouTube

Java Interview Questions and Answers 1.0