📜  带有Spring框架的AOP(1)

📅  最后修改于: 2023-12-03 14:54:03.043000             🧑  作者: Mango

带有Spring框架的AOP

简介

在软件开发中,面向切面编程(AOP)是一个软件设计模式,在其中遵循面向对象编程的一些原则。在AOP中,与主要业务逻辑无关的功能被拆分为多个方面,然后通过这些方面注入主要业务逻辑中。

Spring框架提供了一个强大的AOP实现,可以用于切面编程。Spring AOP可以用来实现横切关注点的分离。当用于切面编程时,Spring AOP提供了一种通过声明方式将横切关注点与业务对象相分离的方法。

Spring框架的AOP实现

Spring AOP使用了代理模式来实现AOP。它通过提供一个代理对象来把切面切入到业务逻辑中。在Spring AOP中,切面由一个拦截器链组成,在该链中定义了切点和横切逻辑。拦截器链中的每一个拦截器都可以对应一个横切逻辑,通过对拦截器链中每个拦截器的组合来实现对同一个切点的多个横切逻辑的组合。

Spring AOP支持两种不同类型的切点实现:

  1. 编程切点,即使用AspectJ切点表达式来定义切点。
  2. 声明式切点,即在XML文件中声明一个切点。
使用Spring框架的AOP
  1. 添加Spring AOP依赖项

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>{spring.version}</version>
    </dependency>
    
  2. 声明一个切面

    @Aspect
    public class LoggingAspect {
    
        @Before("execution(* com.example.service.*.*(..))")
        public void logBefore(JoinPoint joinPoint) {
            System.out.println("logging before...");
        }
    
        @After("execution(* com.example.service.*.*(..))")
        public void logAfter(JoinPoint joinPoint) {
            System.out.println("logging after...");
        }
    }
    
  3. 配置切面和目标对象

    <bean id="loggingAspect" class="com.example.aspect.LoggingAspect" />
    
    <bean id="targetObject" class="com.example.service.MyService" />
    
  4. 启动Spring容器

    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    MyService myService = (MyService) context.getBean("targetObject");
    myService.doSomething();
    
切面通知类型

Spring AOP支持以下四种类型的切面通知:

  1. Before advice:在目标方法执行前执行。
  2. After returning advice:在目标方法返回结果后执行。
  3. After throwing advice:在目标方法抛出异常后执行。
  4. Around advice:包围目标方法,可以在方法执行前和方法执行后执行。
切点表达式

在Spring AOP中,切点表达式用于创建切点,切点用于定义切面将会被应用于哪些类及它们的哪部分方法上。Spring AOP支持两种类型的切点表达式:

  1. execution表达式:用于匹配方法执行。

    execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern) throws-pattern?)
    
    • modifiers:表示方法访问修饰符的字符串,可选。
    • ret-type-pattern:返回类型的完整类名,可选。
    • declaring-type-pattern:声明该方法的完整类名,可选。
    • name-pattern:方法名及其参数类型,必选。
    • param-pattern:表示方法参数类型的字符串,可选。
    • throws-pattern:方法可能抛出的异常类型,可选。
  2. within表达式:用于匹配类及其所有方法。

    within(com.example.service.*)
    
总结

使用Spring AOP可以在不添加任何业务逻辑代码的情况下实现许多横切关注点,使代码更加易于维护。在本文中,我们了解了Spring AOP的简介和它的实现方式,以及如何使用Spring AOP和切点表达式来实现切面编程。