Spring Boot - spring-boot-starter-aop

spring-boot-starter-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>

创建一个Java类UserService.java,它包含一个简单的方法getUser():


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);
    }

}

创建一个启动类Application.java,它用于启动Spring Boot应用程序:


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");
    }

}

在这个示例中,我们创建了一个UserService类,它有一个getUser()
方法用于返回一个用户的信息。然后,我们创建了一个切面类LoggingAspect,它使用@Before和@After注解来定义前置通知和后置通知,这些通知将在UserService类的getUser()
方法执行前后打印日志。最后,在Application类的main()方法中,我们获取UserService的实例并调用getUser()方法。

当你运行这个Spring Boot应用程序时,你将看到在getUser()方法执行前后分别打印了日志信息。

猜你喜欢

转载自blog.csdn.net/qq_43116031/article/details/131135091