SpringBoot使用AOP

本文介绍如何在SpringBoot 2.x中使用AOP实现登录验证功能。通过添加依赖、定义注解、创建切面及测试类,展示了AOP在实际项目中的应用过程,相比传统SSM框架更为简便。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,AOP是什么?

AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2的拦截器设计就是基于AOP的思想,是个比较经典的例子。

2,SpringBoot2.x中使用aop和SSM有什么不同呢?请看案例

第一步:添加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.itpengwei.ideaaop</groupId>
    <artifactId>springboot-aop</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-aop</name>
    <description>Demo project for Spring Boot</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>
        <!--加入aop依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </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>

第二步:编写一个注解,用来当切点使用

package com.itpengwei.aop.common;

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

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NeedLogin {
}

第三步:现在开始写一个切面(注意:因为使用注解开启的aop是没有顺序的,所以我们配置Order使用,让其有优先级)

package com.itpengwei.aop.aops;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Aspect
@Order(1)
@Configuration
public class NeedLoginInterceptor {
    @Pointcut("@annotation(com.itpengwei.aop.common.NeedLogin)")
    public void excudeService() {
    }

    @After("excudeService()")
    public void after() {
        System.out.print("我是after");
    }

    @Around("excudeService()")
    public Object around(ProceedingJoinPoint joinPoint) {
        System.out.println("我是around的前置");
        try {
            joinPoint.proceed();
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("我是around的后置");
        return null;
    }
}

第四步:编写一个测试类,进行测试我们写的切面是不是被织入进去了

package com.itpengwei.aop.controller;

import com.itpengwei.aop.common.NeedLogin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @GetMapping(value = "/user")
    @NeedLogin
    public String test() {
        return "哈哈";
    }
}

接下来我们来看控制台打印的日志,很明显我们的切面成功被织入进去了,是不是比SSM使用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、付费专栏及课程。

余额充值