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

相关推荐
用户47949283569158 分钟前
XSS、CSRF、CSP、HttpOnly 全扫盲:前端安全不只是后端的事
前端·后端·面试
我家领养了个白胖胖14 分钟前
SSE在Spring ai alibaba中同时使用Qwen和DeepSeek模型
java·后端·ai编程
AI科技摆渡27 分钟前
GPT-5.2介绍+ 三步对接教程
android·java·gpt
Java编程爱好者28 分钟前
做了个Java打包工具,可以双击启动了!
后端
猿与禅34 分钟前
Spring Boot 4.0 完整核心特性及实践指南
java·spring boot·后端·spring·重大升级·springboot4.0
平凡运维之路44 分钟前
端口转发
后端
运维@小兵1 小时前
Spring-AI系列——Tool Calling获取当前时间
java·后端·spring
认真敲代码的小火龙1 小时前
【JAVA项目】基于JAVA的养老院管理系统
java·开发语言·课程设计
he___H1 小时前
滑动窗口一题
java·数据结构·算法·滑动窗口
扶苏-su1 小时前
Java---事件处理机制
java·开发语言