Spring Boot 中使用AOP

本文介绍了如何在Spring Boot中使用AOP进行日志记录。首先,通过添加Spring Web和AOP相关依赖,然后创建Controller的web接口。接着,定义AOP切面,使用`@Aspect`标记类并用`@Around`注解实现环绕通知,用于在方法调用前后打印日志。最后,通过访问Controller接口,验证AOP的日志打印功能。
摘要由CSDN通过智能技术生成

1. Spring Boot中的AOP

⏰ 关键代码

  • 🌏 使用 @Aspect@Component注解标记类为切面,并使用@Pointcut定义切入点,使用@Around定义通知
    @Aspect
    @Component
    @Slf4j
    public class AopTestSimple {
         
        /**
         * 定义切入点
         */
        @Pointcut("execution(public * cn.ohbee.demoaop.*Controller.*(..))")
        public void aopTestSimplePointcut() {
         }
    
        /**
         *  定义环绕通知,①解析浏览器请求信息,②获取调取方法的信息,③获取方法执行完的返回结果
         * @param point  通知的第一个固有参数
         */
        @Around("aopTestSimplePointcut()")
        public Object aopTestSimpleAround(ProceedingJoinPoint point) throws Throwable {
         
            //目标方法执行
            Object  proceed = point.proceed();
            ...
            return proceed;
        }
        }
    
⏰ Maven依赖

  • 🌏 pom.xml 中使用如下依赖,如下:
       <dependencies>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter</artifactId>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-test</artifactId>
               <scope>test</scope>
           </dependency>
           <!--web 项目依赖-->
           <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>
       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值