springboot项目使用aop

步骤 1: 创建Spring Boot项目

首先,创建一个新的Spring Boot项目。你可以使用Spring Initializr(https://start.spring.io/)来快速初始化一个项目。

选择以下依赖:

  • Spring Web
  • Spring AOP

点击“Generate”下载项目的压缩包,并解压到你的工作目录。

步骤 2: 定义业务逻辑类

src/main/java/com/example/demo目录下,创建一个新的Java类CalculatorService.java。这个类将提供基本的数学运算功能。

package com.example.demo;

import org.springframework.stereotype.Service;

@Service
public class CalculatorService {

    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}

步骤 3: 创建切面类

接下来,创建一个切面类CalculatorAspect.java。这个类将包含我们需要的横切关注点逻辑。

package com.example.demo;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CalculatorAspect {

    @Around("execution(* com.example.demo.CalculatorService.*(..))")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            return joinPoint.proceed();
        } finally {
            long executionTime = System.currentTimeMillis() - start;
            System.out.println("Method " + joinPoint.getSignature().getName() +
                    " executed in " + executionTime + " ms");
        }
    }

    @Before("execution(* com.example.demo.CalculatorService.*(..))")
    public void logBeforeExecution() {
        System.out.println("Executing method...");
    }

    @AfterReturning(pointcut = "execution(* com.example.demo.CalculatorService.add(int, int))", returning = "result")
    public void logResult(Object result) {
        System.out.println("Addition result: " + result);
    }
}

步骤 4: 配置AOP

为了启用AOP,需要在Spring Boot的配置类上添加@EnableAspectJAutoProxy注解。

打开主类(通常是DemoApplication.java),添加以下内容:

package com.example.demo;

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

@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

步骤 5: 创建测试类

为了验证AOP是否生效,创建一个测试类CalculatorControllerTest.java

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class CalculatorControllerTest {

    @Autowired
    private CalculatorService calculatorService;

    @Test
    public void testAdd() {
        int result = calculatorService.add(10, 5);
        System.out.println("Result of add: " + result);
    }

    @Test
    public void testSubtract() {
        int result = calculatorService.subtract(10, 5);
        System.out.println("Result of subtract: " + result);
    }
}

步骤 6: 运行测试

运行测试类中的方法,观察控制台输出。

你应该会看到类似以下的输出:

Executing method...
Method add executed in 123 ms
Result of add: 15
Addition result: 15

Executing method...
Method subtract executed in 45 ms
Result of subtract: 5

解释

  • @Aspect: 标记这是一个切面类。
  • @Component: 将这个切面类注册为Spring组件,使其能够被扫描到。
  • @Around: 定义一个环绕通知,用于在目标方法执行前后添加逻辑。在这里,我们记录了方法的执行时间。
  • @Before: 在目标方法执行前执行的通知。这里用于打印日志,表示即将执行某个方法。
  • @AfterReturning: 方法成功返回后执行的通知。这里用于记录加法运算的结果。

总结

通过以上步骤,我们在Spring Boot项目中成功地实现了AOP功能。切面类中的各个通知在目标方法的不同生命周期阶段被触发,从而达到了横切关注点与业务逻辑分离的目的。这不仅提高了代码的可维护性,还使得日志记录、性能监控等功能更加轻松和高效。

如果你希望进一步探索,可以尝试添加更多的横切关注点(如事务管理),或者使用不同的通知类型来满足项目的需求。

Spring Boot提供了与Spring AOP集成的支持,可以使用AOP来处理各种方面的问题。下面是使用Spring BootAOP的步骤: 1. 首先,需要在项目中添加Spring AOP的依赖项。可以在Maven或Gradle中添加以下依赖项: Maven: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` Gradle: ``` compile('org.springframework.boot:spring-boot-starter-aop') ``` 2. 创建一个切面类。切面类是用于定义切点和通知的类。可以使用@Aspect注释将它标记为切面类。 3. 在切面类中定义切点。切点是一个表达式,它定义了在何处执行通知。可以使用@Pointcut注解来定义切点。 4. 在切面类中定义通知。通知是在切点上执行的操作。可以使用@Before、@After、@Around等注解来定义通知。 5. 在应用程序中使用切面。可以使用@Autowire注解将切面类注入到目标类中,从而使用切面。 例如,下面是一个使用AOP的简单示例: ```java @Aspect @Component public class LoggingAspect { @Pointcut("execution(* com.example.demo.service.*.*(..))") public void serviceMethods() {} @Before("serviceMethods()") public void logServiceAccess(JoinPoint joinPoint) { System.out.println("Accessed service method: " + joinPoint.getSignature().getName()); } } ``` 在上面的示例中,LoggingAspect是一个切面类。它定义了一个切点serviceMethods(),该切点匹配com.example.demo.service包中的所有方法。它还定义了一个@Before通知,该通知在serviceMethods()切点上执行,并记录访问的服务方法。最后,在应用程序中使用LoggingAspect来提供AOP支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值