您好,欢迎来到百家汽车网。
搜索
您的当前位置:首页Spring AOP 详解

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.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</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 方法。

结果如下:

对程序进行简单的讲解:

整个代码划分为三部分。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baijiahaobaidu.com 版权所有 湘ICP备2023023988号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务