Spring Boot自定义注解

文章目录

  • [Spring Boot自定义注解](#Spring Boot自定义注解)
    • [步骤 1: 定义注解](#步骤 1: 定义注解)
    • [步骤 2: 创建注解处理器](#步骤 2: 创建注解处理器)
    • [步骤 3: 使用注解](#步骤 3: 使用注解)

Spring Boot自定义注解

  在Spring Boot中自定义注解是一个强大的功能,它可以让你以声明式的方式将特定的行为或元数据添加到你的代码中。自定义注解可以用于多种场景,比如权限控制、日志记录、参数校验等。下面是如何在Spring Boot中定义一个简单的自定义注解及其使用的步骤。

步骤 1: 定义注解

  首先,你需要使用Java的元注解(如@Target, @Retention, @Inherited等)来定义一个新的注解。这些元注解指定了你的注解可以应用到哪些Java元素上(如类、方法、字段等),以及注解的生命周期(如只在源码中存在,还是会被编译到字节码中,或者是被JVM运行时可见)。

java 复制代码
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 LogExecutionTime {  
    // 可以在这里定义注解的属性  
    String description() default "No description";  
}

步骤 2: 创建注解处理器

  接下来,你需要创建一个注解处理器,通常是通过使用Spring的AOP(面向切面编程)功能来实现。你可以通过定义一个切面(Aspect)来拦截带有你的自定义注解的方法,并在这些方法执行前后执行特定的逻辑。

java 复制代码
import org.aspectj.lang.annotation.Aspect;  
import org.aspectj.lang.annotation.Before;  
import org.aspectj.lang.annotation.Pointcut;  
import org.aspectj.lang.ProceedingJoinPoint;  
import org.aspectj.lang.annotation.Around;  
import org.aspectj.lang.annotation.After;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.springframework.stereotype.Component;  
  
@Aspect  
@Component  
public class LogAspect {  
  
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);  
  
    // 定义一个切点,用于匹配所有带有@LogExecutionTime注解的方法  
    @Pointcut("@annotation(logExecutionTime)")  
    public void logPointcut(LogExecutionTime logExecutionTime) {}  
  
    // 环绕通知,用于计算方法的执行时间  
    @Around("logPointcut(logExecutionTime)")  
    public Object logExecutionTime(ProceedingJoinPoint joinPoint, LogExecutionTime logExecutionTime) throws Throwable {  
        long start = System.currentTimeMillis();  
        Object proceed = joinPoint.proceed(); // 继续执行目标方法  
        long executionTime = System.currentTimeMillis() - start;  
  
        logger.info("{} executed in {} ms. Description: {}",   
            joinPoint.getSignature().toShortString(),   
            executionTime,   
            logExecutionTime.description());  
  
        return proceed;  
    }  
}

步骤 3: 使用注解

  现在,你可以在你的Spring Boot应用的任何地方使用@LogExecutionTime注解了,只需将其添加到任何方法上,并可选地提供一个描述。

java 复制代码
@RestController  
@RequestMapping("/api")  
public class MyController {  
  
    @LogExecutionTime(description = "This is a test method")  
    @GetMapping("/test")  
    public ResponseEntity<String> testMethod() {  
        // 模拟一些操作  
        try {  
            Thread.sleep(1000); // 假设这个方法需要一些时间来完成  
        } catch (InterruptedException e) {  
            Thread.currentThread().interrupt();  
        }  
        return ResponseEntity.ok("Test method executed");  
    }  
}

  当testMethod被调用时,LogAspect会拦截这个调用,并在方法执行前后执行特定的逻辑(在这个例子中,是记录方法的执行时间)。

  通过上述步骤,你可以在Spring Boot应用中定义和使用自定义注解来增强你的代码功能和可读性。

相关推荐
2501_9481069110 分钟前
计算机毕业设计之基于jsp教科研信息共享系统
java·开发语言·信息可视化·spark·课程设计
TanYYF11 分钟前
spring ai入门教程二
java·人工智能·spring
SeeYa-J24 分钟前
Spring IOC(Inversion of Control)
java·spring·rpc
宠友信息1 小时前
多端数据互通场景下Spring Boot仿小红书源码结构设计
数据库·spring boot·redis·缓存·架构
不会c+1 小时前
02-SpringBoot配置文件
java·spring boot·后端
AI 大模型学习不踩坑1 小时前
OpenClaw 完整教程:从安装到使用(官方脚本版)
java·人工智能·神经网络·机器学习·计算机视觉·自然语言处理·openclaw
Listen·Rain2 小时前
数据库流式查询
java·数据库
彦为君2 小时前
算法思维与经典智力题
java·前端·redis·算法
翔云 OCR API2 小时前
慧视扫描王-财务少加班
java·自动化
雨辰AI2 小时前
生产级实战:人大金仓 V9 标准化运维手册(日常巡检 + 监控告警 + 应急处置)
java·运维·数据库·后端