📜  Spring Boot AOP(1)

📅  最后修改于: 2023-12-03 15:35:02.925000             🧑  作者: Mango

Spring Boot AOP

什么是AOP

AOP(Aspect Oriented Programming)面向切面编程,是一种编程思想,可以通过将应用程序分解成多个关注点(即切面)来提高代码的复用性,效率和可维护性。

Spring Boot AOP的使用

Spring Boot提供了强大的AOP模块来帮助我们实现AOP。下面,我们将使用Spring Boot AOP模块来演示如何捕获方法执行前后的日志信息。

引入依赖

首先,在我们的pom.xml文件中添加spring-boot-starter-aop依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
编写切面类

我们需要定义一个切面类,通过在该类上声明@Aspect注解来告诉Spring Boot这是一个切面类。在切面类中,我们可以定义多个切点,每个切点是一个正则表达式,用来匹配需要拦截的类和方法。我们可以在切面类中定义多个通知,包括@Before、@After、@AfterReturning、@AfterThrowing和@Around等。

@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(* com.example.demo.service.*.*(..))")
    public void serviceLog() {}

    @Before("serviceLog()")
    public void doBefore(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        logger.info("Start executing {}.{}", signature.getDeclaringTypeName(), signature.getName());
    }

    @AfterReturning(returning = "result", pointcut = "serviceLog()")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        logger.info("Finished executing {}.{}. Returned value is: {}", signature.getDeclaringTypeName(), signature.getName(), result);
    }

    @AfterThrowing(throwing = "ex", pointcut = "serviceLog()")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable ex) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        logger.error("Failed executing {}.{}. Exception message is: {}", signature.getDeclaringTypeName(), signature.getName(), ex.getMessage());
    }

}

在上面这个切面类中,我们定义了一个切点serviceLog,用来匹配com.example.demo.service包下所有的方法。我们还定义了3个通知,分别是@Before、@AfterReturning和@AfterThrowing。

  • @Before通知在目标方法执行之前执行。我们使用JoinPoint对象来获取该方法的签名,包括其类名、方法名和参数列表。我们通过Logger对象将该信息记录在日志中。
  • @AfterReturning通知在目标方法成功执行之后执行。我们同样使用JoinPoint对象来获取该方法的签名,并且在此处记录该方法的执行结果。
  • @AfterThrowing通知在目标方法抛出异常时执行。我们也使用JoinPoint对象获取该方法的签名,并记录异常信息。
启动应用程序

最后,在主程序中添加@EnableAspectJAutoProxy注解开启自动代理,以便AOP能够实现。我们启动程序并调用相关的service方法,日志信息将被记录。

@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {

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

}
总结

通过Spring Boot AOP的帮助,我们可以轻松地实现通用功能(如日志记录、性能监控等)的分离和重用。Spring Boot AOP使用简单,但却强大且具有灵活性,非常适合中小规模项目快速开发。