Spring Boot - spring-boot-starter-aop

スプリングブートスターターAOP

仕事では、 spring-boot-starter-aop は、ロギング、パフォーマンス監視、トランザクション管理などのアスペクト プログラミングをアプリケーションに実装するためによく使用されます。例としてログを使用した完全なコード例を次に示します。

Maven プロジェクトを作成し、次の依存関係を pom.xml ファイルに追加します。

<dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Starter AOP -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
    </dependencies>

単純なメソッド getUser() を含む Java クラス UserService.java を作成します。


package com.lfsun.springbootstarteraop;

import org.springframework.stereotype.Component;

@Component
public class UserService {
    
    

    public String getUser(String username) {
    
    
        System.out.println("Fetching user: " + username);
        return "User: " + username;
    }

}

アスペクト クラス LoggingAspect.java を作成します。これは、UserService クラスのメソッド実行の前後にログを出力します。

package com.lfsun.springbootstarteraop;

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

@Aspect
@Component
public class LoggingAspect {
    
    

    @Before("execution(* UserService.getUser(String)) && args(username)")
    public void beforeAdvice(JoinPoint joinPoint, String username) {
    
    
        System.out.println("Fetching user beforeAdvice: " + username);
    }

    @After("execution(* UserService.getUser(String)) && args(username)")
    public void afterAdvice(JoinPoint joinPoint, String username) {
    
    
        System.out.println("Finished fetching user afterAdvice: " + username);
    }

}

Spring Boot アプリケーションの起動に使用される起動クラス Application.java を作成します。


package com.lfsun.springbootstarteraop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SpringBootStarterAopApplication {
    
    

    public static void main(String[] args) {
    
    
        ConfigurableApplicationContext context = SpringApplication.run(SpringBootStarterAopApplication.class, args);

        UserService userService = context.getBean(UserService.class);
        userService.getUser("lfsun666");
    }

}


この例では、ユーザーに関する情報を返すgetUser() メソッドを持つ UserService クラスを作成します。
次に、アスペクト クラス LoggingAspect を作成しました。このクラスは @Before および @After アノテーションを使用して事前通知と事後通知を定義し、 UserService クラスのgetUser() メソッドの実行前後にログを出力します。最後に、Application クラスの main() メソッドで、UserService のインスタンスを取得し、getUser() メソッドを呼び出します。

この Spring Boot アプリケーションを実行すると、getUser() メソッドの実行の前後にログ メッセージが出力されるのがわかります。

おすすめ

転載: blog.csdn.net/qq_43116031/article/details/131135091