SpringBoot使用AOP

本文介绍SpringBoot中使用Spring AOP。

简介

AOP简介

AOP可能对于广大开发者耳熟能详,它是Aspect Oriented Programming的缩写,翻译成中文就是:面向切面编程。这个可能是面试中经常提到的问题,同时它也是Spring框架中一个重大的特性,AOP主要实现的目的是针对业务处理过程中的切面进行提取,它所面对的是处理过程中的某个步骤或阶段,以获得逻辑过程中各部分之间低耦合性的隔离效果,对于我们开发中最常见的可能就是日志记录,事务处理,异常处理等等。

SpringBoot中使用AOP

接下来介绍SpringBoot项目中如何运用AOP。

新建项目

新建一个SpringBoot项目,在pom文件中加入AOP依赖,完整代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dalaoyang</groupId>
    <artifactId>springboot_aop</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_aop</name>
    <description>springboot_aop</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>
复制代码

创建切面

一 直接使用切面

新建一个日志切面类,假设我们需要一个类来打印进入方法或方法执行后需要打印的日志。

新建一个切面类

新建类LogAspect,完整代码如下:

package com.dalaoyang.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.*;

@Aspect
@Component
public class LogAspect {
    @Pointcut("execution(public * com.dalaoyang.controller.*.*(..))")
    public void LogAspect(){}

    @Before("LogAspect()")
    public void doBefore(JoinPoint joinPoint){
        System.out.println("doBefore");
    }

    @After("LogAspect()")
    public void doAfter(JoinPoint joinPoint){
        System.out.println("doAfter");
    }

    @AfterReturning("LogAspect()")
    public void doAfterReturning(JoinPoint joinPoint){
        System.out.println("doAfterReturning");
    }

    @AfterThrowing("LogAspect()")
    public void deAfterThrowing(JoinPoint joinPoint){
        System.out.println("deAfterThrowing");
    }

    @Around("LogAspect()")
    public Object deAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("deAround");
        return joinPoint.proceed();
    }

}

复制代码

其中:

  • @Aspect 表明是一个切面类
  • @Component 将当前类注入到Spring容器内
  • @Pointcut 切入点,其中execution用于使用切面的连接点。使用方法:execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选)) ,可以使用通配符匹配字符,*可以匹配任意字符。
  • @Before 在方法前执行
  • @After 在方法后执行
  • @AfterReturning 在方法执行后返回一个结果后执行
  • @AfterThrowing 在方法执行过程中抛出异常的时候执行
  • @Around 环绕通知,就是可以在执行前后都使用,这个方法参数必须为ProceedingJoinPoint,proceed()方法就是被切面的方法,上面四个方法可以使用JoinPoint,JoinPoint包含了类名,被切面的方法名,参数等信息。

二 利用自定义注解使用AOP

新建自定义注解

新建自定义注解,新建注解与新建接口类似,将interface改为@interface即可。

package com.dalaoyang.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DoneTime {
    String param() default "";
}

复制代码
创建自定义注解对应切面

创建自定义注解对应切面,与上一中情况的切面类似,这里就不在赘述了,代码如下:

package com.dalaoyang.aspect;

import com.dalaoyang.annotation.DoneTime;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class DoneTimeAspect {

    @Around("@annotation(doneTime)")
    public Object around(ProceedingJoinPoint joinPoint, DoneTime doneTime) throws Throwable {
        System.out.println("方法开始时间是:"+new Date());
        Object o = joinPoint.proceed();
        System.out.println("方法结束时间是:"+new Date()) ;
        return o;
    }
}

复制代码

创建Controller测试

创建一个IndexController进行测试,其实就是两个普通的Web请求方法,其中index使用了自定义注解,index2没有使用自定义注解,完整代码如下:

package com.dalaoyang.controller;

import com.dalaoyang.annotation.DoneTime;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class IndexController {

    @GetMapping("/index")
    @DoneTime(param = "IndexController")
    public String index(){
        System.out.println("方法执行");
        return "hello dalaoyang";
    }

    @GetMapping("/index2")
    public String index2(){
        System.out.println("方法2执行");
        return "hello dalaoyang";
    }
}
复制代码

运行测试

启动项目,在浏览器访问http://localhost:8080/index,控制台如下:

在浏览器访问http://localhost:8080/index2,控制台如下:

总结

本文只是简单介绍一下SpringBoot使用Spring AOP,当然它可能还有其他使用方法,具体的情况需要根据我们实际情况来使用。

源码下载 :大老杨码云

### Spring Boot AOP 使用教程 #### 1. 引入依赖 为了在 Spring Boot使用 AOP,需要引入 `spring-boot-starter-aop` 的 Maven 或 Gradle 依赖。以下是 Maven 配置示例: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> ``` 此配置用于支持 AOP 编程功能[^1]。 --- #### 2. 创建基础项目结构 创建一个标准的 Spring Boot 应用程序入口类作为项目的起点。以下是一个简单的例子: ```java package cn.juwatech.logdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class LogDemoApplication { public static void main(String[] args) { SpringApplication.run(LogDemoApplication.class, args); } } ``` 这是构建 Spring Boot 项目的基础部分[^2]。 --- #### 3. 定义切面 (Aspect) 定义一个切面类并标注为 `@Component` 和 `@Aspect` 注解。通过切点表达式指定哪些方法会被拦截,并提供前置通知 (`@Before`)、后置通知 (`@AfterReturning`) 等增强逻辑。 下面展示了一个完整的日志记录切面实现: ```java package cn.juwatech.logdemo.aspect; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.AfterReturning; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.aspectj.lang.JoinPoint; import org.springframework.stereotype.Component; @Component @Aspect public class LoggingAspect { private final Logger logger = LoggerFactory.getLogger(this.getClass()); // 切点表达式:匹配 com.example.service 包下的所有公共方法 @Before("execution(public * com.example.service.*.*(..))") public void logMethodEntry(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); logger.info("Entering method: {} with arguments {}", methodName, arguments); } @AfterReturning(pointcut = "execution(public * com.example.service.*.*(..))", returning = "result") public void logMethodExit(Object result) { logger.info("Exiting method with result {}", result); } } ``` 上述代码展示了如何利用 AOP 实现方法调用的日志记录功能][^[^23]。 --- #### 4. 测试服务类 编写一个测试的服务类来验证切面的功能是否正常工作。 ```java package com.example.service; import org.springframework.stereotype.Service; @Service public class SampleService { public String performTask() { return "Task completed successfully"; } } ``` 当调用 `performTask()` 方法时,上面定义的切面将会自动生效并打印对应的日志信息。 --- #### 5. 运行应用程序 启动 Spring Boot 应用程序后,访问任何由切面覆盖的方法即可看到日志输出效果。 Spring AOP 基于代理机制运行,在实际应用中会根据目标对象是否有接口决定采用 JDK 动态代理还是 CGLIB 代理[^4]。 --- ### 总结 以上内容涵盖了在 Spring Boot 中启用 AOP 所需的关键步骤以及具体实现细节。通过这些操作,开发者能够轻松地将诸如日志记录等功能集成到自己的项目当中。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值