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

相关推荐
刚子编程1 小时前
我用 ASP.NET Core 做了个水稻病虫害检查系统
后端·asp.net
谢亮_vipxieliang1 小时前
用 PHP 构建轻量级 REST API:从路由到鉴权的完整实践
开发语言·后端·php
Escalating_xu1 小时前
【C 语言】数据在内存中的存储:补码、大小端、整型陷阱与 IEEE 754 全解析
java·c语言·网络
灯澜忆梦2 小时前
【面向对象编程C++】| 基础语法
java·c++·算法
一个风轻云淡2 小时前
GCC 和 GDB命令简单解读
java·linux·前端
省钱兄--zs2 小时前
西安24小时自助健身房解决方案实战:系统开发与部署全流程指南
java·spring boot·系统架构·intellij-idea·需求分析
资料库012 小时前
Linux 8个常见运维故障排查
java·linux·运维
要开心吖ZSH2 小时前
MySQL 慢 SQL 排查操作手册-个人笔记版
java·笔记·sql·mysql·慢查询
Joy T3 小时前
Spring AI 接入已有 Java 项目的三种架构设计
java·人工智能·springai·ai入门·chatclient·ai service·ai能力接入