原文: https://howtodoinjava.com/spring-boot2/aop-aspectj/

学习在 Spring Boot 应用程序中实现 AOP,并使用 AspectJ 添加不同的 aop 建议,以支持诸如日志记录,性能分析,缓存和事务管理之类的跨领域关注点。

阅读更多: Spring AOP 教程

1. 使用 Spring Boot 设置 AOP

1.1. Maven

在 Spring Boot 中设置 AOP 需要包括spring-boot-starter-aop依赖项。 它将spring-aopaspectjweaver依赖项导入到应用程序中。 入门 pom.xml

pom.xml

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>

1.2. 启用/禁用自动配置

导入以上依赖项会触发AopAutoConfiguration,这会使用@EnableAspectJAutoProxy注解启用 AOP。

如果application.properties中的spring.aop.auto = false不激活自动配置。

application.properties

  1. #spring.aop.auto = false //'false' disables the auto configuration

1.3. 使用@Aspect创建切面

可以在 Spring 运行中使用注解@Aspect注解创建一个切面,并使用@Component注解在 bean 容器中注册。

在切面类中,我们可以根据需要创建建议。 例如,下面的类在包com.howtodoinjava.aop中所有类内的方法上对建议应用。 它捕获方法的开始时间和结束时间,并将总的方法执行时间记录在日志文件中。

LoggingAspect.java

  1. import org.apache.logging.log4j.LogManager;
  2. import org.apache.logging.log4j.Logger;
  3. import org.aspectj.lang.ProceedingJoinPoint;
  4. import org.aspectj.lang.annotation.Around;
  5. import org.aspectj.lang.annotation.Aspect;
  6. import org.aspectj.lang.reflect.MethodSignature;
  7. import org.springframework.stereotype.Component;
  8. import org.springframework.util.StopWatch;
  9. @Aspect
  10. @Component
  11. public class LoggingAspect
  12. {
  13. private static final Logger LOGGER = LogManager.getLogger(LoggingAspect.class);
  14. @Around("execution(* com.howtodoinjava.aop..*(..)))")
  15. public Object profileAllMethods(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
  16. {
  17. MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
  18. //Get intercepted method details
  19. String className = methodSignature.getDeclaringType().getSimpleName();
  20. String methodName = methodSignature.getName();
  21. final StopWatch stopWatch = new StopWatch();
  22. //Measure method execution time
  23. stopWatch.start();
  24. Object result = proceedingJoinPoint.proceed();
  25. stopWatch.stop();
  26. //Log method execution time
  27. LOGGER.info("Execution time of " + className + "." + methodName + " "
  28. + ":: " + stopWatch.getTotalTimeMillis() + " ms");
  29. return result;
  30. }
  31. }

1.4. 示例

创建一个简单的服务类来测试以上建议。

DomainService.java

  1. @Service
  2. public class DomainService
  3. {
  4. public Object getDomainObjectById(Long id)
  5. {
  6. try {
  7. Thread.sleep(new Random().nextInt(2000));
  8. } catch (InterruptedException e) {
  9. //do some logging
  10. }
  11. return id;
  12. }
  13. }

创建一个测试类并执行给定的方法并注意日志。

AopSpringBootTest.java

  1. import org.junit.Test;
  2. import org.junit.runner.RunWith;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.test.context.SpringBootTest;
  5. import org.springframework.test.context.junit4.SpringRunner;
  6. @RunWith(SpringRunner.class)
  7. @SpringBootTest
  8. public class AopSpringBootTest
  9. {
  10. @Autowired
  11. private DomainService service;
  12. @Test
  13. public void testGetDomainObjectById()
  14. {
  15. service.getDomainObjectById(10L);
  16. }
  17. }

Console

  1. 2019-11-07T21:02:58.390+0530 INFO Execution time of DomainService.getDomainObjectById :: 1145 ms

如我们所见,AOP 建议已应用于服务方法。

2. 建议类型

在 Aspectj AOP 中有五种类型的建议。

  1. @Before :在连接点之前执行的建议,但是它不能阻止执行流程前进到连接点(除非它引发异常)。
  2. @AfterReturning :连接点正常完成后要执行的建议。
  3. @AfterThrowing :如果方法因抛出异常而退出,则要执行的建议。
  4. @After :无论连接点退出的方式如何(正常或异常返回),都将执行建议。
  5. @Around :围绕连接点的建议,例如方法调用。

3. 结论

使用 Spring 运行实现 AOP 只需很少的工作,并且一旦添加spring-boot-starter-aop依赖项,我们就准备添加切面。

每当我们想禁用 aop 自动配置时,我们都可以通过切换到 false轻松完成。

创建切面和建议就像添加一些注解一样简单,例如@Aspect@Around等。

学习愉快!

下载源码