Files
blog-press/docs/Web-Backend/SpringBoot/SpringBoot-Annotation.md
2025-12-30 19:03:46 +08:00

72 lines
4.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: SpingBoot注解
date: 2025-12-30
---
# 一、注解
## 1.1 定义
  注解Annotation是 JDK5.0 引入的特性,可以理解为:给代码添加的 “元数据”(描述数据的数据),就像给代码贴标签,**本身不直接影响代码执行,但可以被编译器、框架(如 SpringBoot读取并做相应处理**。
## 1.2 分类
| 类型 | 核心作用 | 典型示例 |
|----------------|--------------------|------------------|
| 源码注解 | 仅在源码编译阶段生效,编译后注解消失 | `@Override` |
| 编译时注解 | 编译期生效注解信息保留到class文件但JVM运行时不加载 | Lombok的`@Data` |
| 运行时注解 | 整个生命周期都存在(源码→编译→运行),可通过反射动态获取注解信息 | SpringBoot的`@RestController``@Service``@Transactional` |
## 1.3 示例
```java
import java.lang.annotation.*;
// 1. 注解的元注解(描述注解的注解)
@Target(ElementType.METHOD) // 注解作用在方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时保留,可通过反射获取
@Documented // 生成Javadoc时包含该注解
public @interface MyAnnotation {
// 注解的属性(类似方法,可设置默认值)
String value() default "默认描述";
int num() default 0;
}
// 2. 使用自定义注解
public class AnnotationTest {
@MyAnnotation(value = "测试方法", num = 10)
public void test() {
System.out.println("执行测试方法");
}
// 3. 通过反射读取注解
public static void main(String[] args) throws NoSuchMethodException {
// 获取方法对象
java.lang.reflect.Method method = AnnotationTest.class.getMethod("test");
// 判断方法是否有该注解
if (method.isAnnotationPresent(MyAnnotation.class)) {
// 获取注解实例
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
// 读取注解属性
System.out.println("注解value" + annotation.value()); // 输出:测试方法
System.out.println("注解num" + annotation.num()); // 输出10
}
}
}
```
  @Target指定注解能作用的位置如ElementType.METHOD= 方法、ElementType.TYPE= 类 / 接口、ElementType.FIELD= 字段)。
  @Retention指定注解的保留阶段RUNTIME是 SpringBoot 注解最常用的)
  首先定义注解的@Target和@Retention信息然后设置注解的属性类似于方法的参数比如这里的value和num需要在使用的时候通过命名参数的形式传递过来。如果是RUNTIME类型的注解可以通过反射来获取方法和注解的参数实现自定义逻辑功能。
# 二、SpringBoot核心注解
## 2.1 启动类注解
  @SpringBootApplication为SpringBoot启动类注解,由以下三个注解组成:
1. @Configuration:标记类为配置类(替代 XML 配置)
2. @EnableAutoConfiguration开启自动配置SpringBoot 核心,自动配置 Tomcat、数据库连接等
3. @ComponentScan:扫描当前包及子包下的 @Component@Service 等注解的类,纳入 Spring 容器管理
## 2.2 组件注册注解
| 注解 | 作用 | 使用场景 |
|----------------|--------------------------|------------------------------------------------------------------|
| @Component | 通用组件注解 | 通用工具类、非业务层类 |
| @Controller | 控制器注解 | MVC 的控制层(返回页面) |
| @RestController| REST 控制器 | API 接口层(返回 JSON/XML= @Controller + @ResponseBody |
| @Service | 服务层注解 | 业务逻辑层 |
| @Repository | 数据访问层注解 | DAO 层 / 持久层(如 MyBatis 的 Mapper 接口) |