使用自定义注解配置aop

文章展示了如何在SpringBoot项目中使用MyBatisPlus进行数据操作,并结合AOP(面向切面编程)实现自定义注解LogAnno,以此来记录方法的执行时间和日志信息。通过在控制器类和方法上应用LogAnno,可以自动捕获和记录相关日志,提高开发效率。
摘要由CSDN通过智能技术生成

pom文件

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

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.10.graal</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!--        基于子类的动态代理-->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!--aop依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!--        @Slf4j依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

    </dependencies>

注解类LogAnno

package com.hao.aop;

import java.lang.annotation.*;

/**
 * @interface 是一个关键字,用于定义自定义注解(Custom Annotation)。通过使用 @interface 关键字,可以创建一个新的注解类型
 *
 * @Documented 用于指示被注解的元素应该包含在生成的API文档中。它被用于注解声明上,用于帮助生成文档工具将注解信息包含在生成的文档中。当一个注解被标记为 @Documented 时,
 * 它的元数据将会出现在生成的API文档中,以便开发人员可以看到该注解的存在和使用。这对于公共API的文档化非常有用,因为它可以提供关于注解的详细信息和使用示例,以便使用者
 * 了解如何正确地使用注解。
 * 需要注意的是,@Documented 仅仅是一个标记注解,它本身不提供任何元数据或行为。它只是为了告诉文档生成工具将被注解的元素包含在文档中。
 *
 * @Retention 用于指定被注解的元素在代码运行时的生命周期。它被用于注解声明上,用于控制注解的保留策略。
 * RetentionPolicy.RUNTIME:注解存在于源代码、编译后的字节码和运行时,可以通过反射机制在运行时获取注解信息
 *
 * @Target 用于指定其他注解可以应用的程序元素类型。它被用于注解声明上,帮助限制注解可以应用的位置。
 * ElementType.TYPE:可以应用于类、接口或枚举类型
 * ElementType.METHOD:可以应用于方法
 *
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnno {

}

切面类LogAspect

package com.hao.aop;


import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;

@Aspect
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LogAspect {

    /**
     * 配置切点
     */
    @Pointcut("@annotation(com.hao.aop.LogAnno) || @within(com.hao.aop.LogAnno)")
    public void pointCutLog() {

    }

    @Around("pointCutLog()")
    public Object saveLog(ProceedingJoinPoint point) throws Throwable {
        Instant startTime = Instant.now();
        Object result = null;
        //前置通知
        MethodSignature methodName = (MethodSignature) point.getSignature();//方法名
        log.info("前置通知,伟大的aop,开始打印了" + methodName);
        String body = JSONUtil.toJsonStr(point.getArgs());//传参
        try {
            result = point.proceed();//切入点方法
            //后置通知
            Instant endTime = Instant.now();
            log.info("after通知:"+ Duration.between(startTime,endTime));//方法执行时间
        } catch (Exception e) {
            //异常通知
            log.error(methodName.getName(), e);
            log.info("exception通知");
        } finally {
            //最终通知
            log.info("finally通知");
        }
        return result;
    }
}

将注解@LogAnno用到想要拦截的方法或者类上,用到方法上

    @LogAnno
    @RequestMapping("hello")
    public String hello() throws InterruptedException {
        Thread.sleep(3000);
        System.out.println("today is beautiful day!");
        return "today is beautiful day";
    }

用到类上

package com.hao.controll;

import com.hao.aop.LogAnno;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("test")
@LogAnno
public class TestController {


    @RequestMapping("hello")
    public String hello() throws InterruptedException {
        Thread.sleep(3000);
        System.out.println("today is beautiful day!");
        return "today is beautiful day";
    }

    @RequestMapping("smell")
    public String smell() {
        System.out.println(" a particular smell!");
        return " a particular smell!";
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值