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应用中定义和使用自定义注解来增强你的代码功能和可读性。

相关推荐
J_liaty16 分钟前
Spring Boot拦截器与过滤器深度解析
java·spring boot·后端·interceptor·filter
短剑重铸之日24 分钟前
《7天学会Redis》Day2 - 深入Redis数据结构与底层实现
数据结构·数据库·redis·后端
码事漫谈41 分钟前
从C++到C#的转型完全指南
后端
码事漫谈1 小时前
TCP心跳机制:看不见的“生命线”
后端
亲爱的非洲野猪1 小时前
Java锁机制八股文
java·开发语言
rgeshfgreh1 小时前
C++字符串处理:STL string终极指南
java·jvm·算法
Zoey的笔记本1 小时前
「支持ISO27001的GTD协作平台」数据生命周期管理方案与加密通信协议
java·前端·数据库
lpfasd1231 小时前
Spring Boot 4.0.1 时变更清单
java·spring boot·后端
N***H4861 小时前
SpringBoot3.3.0集成Knife4j4.5.0实战
java
梦梦代码精2 小时前
《全栈开源智能体:终结企业AI拼图时代》
人工智能·后端·深度学习·小程序·前端框架·开源·语音识别