springboot使用AOP

1、添加依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2、设置切面

@Aspect
@Configuration
public class AopConfig {

    @Pointcut("execution(* com.glodon.springboot.controller.AopController.test*(..))")
    public void excudeService(){}

    @Before("excudeService()")
    public void before() {
        System.out.println("切面before执行了");
    }

    @After("excudeService()")
    public void after() {
        System.out.println("切面after执行了");
    }

    @AfterReturning("excudeService()")
    public void afterReturning() {
        System.out.println("切面afterReturning执行了");
    }

    @AfterThrowing("excudeService()")
    public void afterThrowing() {
        System.out.println("切面afterThrowing执行了");
    }

    @Around("excudeService()")
    public Object around(ProceedingJoinPoint thisJoinPoint){
        Object obj = null;
        System.err.println ("切面around before执行了");
        try {
            thisJoinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace ();
        }
        System.err.println ("切面around after执行了");
        return obj;
    }
    
}

 3、测试类

@RestController
@RequestMapping(value = "/api/aop")
public class AopController {

    @GetMapping(value = "/test")
    public String testAOP() {
        System.out.println("test");
        return "test";
    }

}

 4、AOP顺序

通过注解方式配置AOP是无序的,若想有序则需显式定义一个Advisor的实现了Ordered的子类的bean,并且给order赋值


更多:

SpringBoot简介

SpringBoot-HelloWorld

spring boot 框架解析

spring boot 部署、启动

spring boot配置文件

spring boot 全局异常捕捉

springboot使用fastjson

springboot使用定时任务、异步

springboot使用AOP

springboot使用拦截器

springboot输出日志

springboot集成hibernate-jpa方式


### 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、付费专栏及课程。

余额充值