Spring AOP 详解

文章目录

  • 一、AOP 概述
  • 二、Spring AOP 快速入门
    • 2.1 引入 AOP 依赖:
    • 2.2 编写 AOP 程序:
  • 三、Spring AOP 详解
    • 3.1 Spring AOP 核心概念:
      • 3.1.1 切点(Pointcut):
      • 3.1.2 连接点(Join Point):
      • 3.1.3 通知(Advice):
      • 3.1.4 切面(Aspect):
    • 3.2 通知类型:
    • 3.3 @PointCut:
    • 3.4 切面优先级 @Order:
    • 3.5 切点表达式:
      • 3.5.1 execution 表达式:
      • 3.5.2 @annotation:
    • 3.6 Spring AOP 的实现方式(常见面试题):
  • 四、代理模式

Spring 框架有两大核心 IoC,AOP。在前面我们已经学习过了 IoC 的相关知识,今天就让我们开始 AOP 的学习。

一、AOP 概述

Aspect Oriented Programming(面向切面编程)。

切面就是指某一类特定问题,所以 AOP 也可以理解为面向特定方法编程。

**AOP 是一种思想,是对某一类事情的集中处理。**Spring AOP 是其中的一种实现方式。

AOP 的作用:在程序运行期间,在不修改源代码的基础上,对已有方法进行增强(无侵入性:解耦)。

二、Spring AOP 快速入门

我们先通过下面的程序体验下 AOP 的开发,并掌握 Spring 中 AOP 的开发步骤。

2.1 引入 AOP 依赖:

在 pom.xml 文件中添加配置:

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-aopartifactId>
dependency>

2.2 编写 AOP 程序:

@Aspect
@Slf4j
@Component
public class TestAspect {
   
    @Around("execution(* com.example.demo.controller.*.*(..))")
    public Object demo(ProceedingJoinPoint joinPoint) throws Throwable {
   
        log.info("方法执行前执行");
        Object result = joinPoint.proceed();
        log.info("方法执行后执行");
        return result;
    }
}

controller 类:

@RequestMapping("/test")
@RestController
@Slf4j
public class TestController {
   

    @RequestMapping("/t1")
    public void test1(){
   
        log.info("我是 test1");
    }
}

调用 controller 中的 test1 方法。

结果如下:

Spring AOP 详解_第1张图片

对程序进行简单的讲解:

  1. @Aspect:标识这是一个切面类。

  2. @Around:环绕通知,在目标方法的前后都会被执行。后面的表达式表示对哪些方法进行增强。

  3. ProceedingJoinPoint.proceed()让原始方法执行。

整个代码划分为三部分。

Spring AOP 详解_第2张图片

通过上面的程序,我们也可以感受到 AOP 面向切面编程的一些优势:

  1. 代码无侵入:不修改原始的业务方法,就可以对原始的业务方法进行了功能的增强或者是功能的改变。
  2. 减少了重复代码。
  3. 提高开发效率。
  4. 维护方便。

三、Spring AOP 详解

3.1 Spring AOP 核心概念:

3.1.1 切点(Pointcut):

切点(Pointcut),也称之为"切入点"。

Pointcut 的作用就是提供一组规则(使用 AspectJ pointcut expression language 来描述),告诉程序对哪些方法来进行功能增强。

你可能感兴趣的:(JavaWeb,spring,java,数据库)