Spring Boot 中常用注解总结(AI工程化)

目录

一、核心启动与配置注解

[1. @SpringBootApplication](#1. @SpringBootApplication)

[2. @Configuration](#2. @Configuration)

[3. @EnableAutoConfiguration](#3. @EnableAutoConfiguration)

[4. @ComponentScan](#4. @ComponentScan)

二、组件注册注解

[1. @Component](#1. @Component)

[2. @Controller](#2. @Controller)

[3. @RestController](#3. @RestController)

[4. @Service](#4. @Service)

[5. @Repository](#5. @Repository)

三、依赖注入注解

[1. @Autowired](#1. @Autowired)

[2. @Resource](#2. @Resource)

[3. @Qualifier](#3. @Qualifier)

[四、请求处理注解(Web 层)](#四、请求处理注解(Web 层))

[1. @RequestMapping](#1. @RequestMapping)

[2. @GetMapping / @PostMapping / @PutMapping / @DeleteMapping](#2. @GetMapping / @PostMapping / @PutMapping / @DeleteMapping)

[3. @PathVariable](#3. @PathVariable)

[4. @RequestParam](#4. @RequestParam)

[5. @RequestBody](#5. @RequestBody)

[6. @RequestHeader](#6. @RequestHeader)

五、配置读取注解

[1. @Value](#1. @Value)

[2. @ConfigurationProperties](#2. @ConfigurationProperties)

[3. @PropertySource](#3. @PropertySource)

六、事务管理注解

[1. @Transactional](#1. @Transactional)

七、条件注解(按需配置)

[1. @ConditionalOnClass / @ConditionalOnMissingClass](#1. @ConditionalOnClass / @ConditionalOnMissingClass)

[2. @ConditionalOnProperty](#2. @ConditionalOnProperty)

八、其他常用注解

[1. @Bean](#1. @Bean)

[2. @Scope](#2. @Scope)

[3. @Lazy](#3. @Lazy)

总结


Spring Boot 基于 Spring 框架,通过大量注解简化了配置和开发流程。以下我会按照核心功能分类,系统梳理 Spring Boot 中最常用的注解,包含定义、作用、实用场景和可运行的示例代码,确保你能快速理解和使用。

一、核心启动与配置注解

1. @SpringBootApplication

定义 :Spring Boot 核心注解,是 @Configuration、@EnableAutoConfiguration、@ComponentScan 的组合注解。

作用:标记主类,触发自动配置、组件扫描和配置类加载。

实用场景:Spring Boot 项目的入口类必须添加此注解。

示例

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; // 核心启动注解,扫描当前包及子包下的所有组件 @SpringBootApplication public class DemoApplication { public static void main(String[] args) { // 启动 Spring Boot 应用 SpringApplication.run(DemoApplication.class, args); } } |

2. @Configuration

定义 :标记类为配置类,替代传统 XML 配置文件,类中可定义 @Bean 方法。

作用:声明该类是配置类,Spring 会扫描并加载其中的 Bean 定义。

实用场景:自定义 Bean 配置(如第三方组件初始化)。

示例

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Configuration public class AppConfig { // 定义一个线程池 Bean,名称为 "taskExecutor" @Bean(name = "taskExecutor") public ExecutorService taskExecutor() { return Executors.newFixedThreadPool(10); } } |

3. @EnableAutoConfiguration

定义:启用 Spring Boot 自动配置机制,根据类路径下的依赖自动配置 Bean。

作用:无需手动配置,Spring Boot 自动识别依赖并初始化相关组件(如引入 spring-boot-starter-web 则自动配置 Tomcat、Spring MVC)。

实用场景 :配合 @SpringBootApplication 使用(无需单独声明),也可单独用于自定义自动配置范围。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| // 单独使用(一般不推荐,优先用 @SpringBootApplication) @Configuration @EnableAutoConfiguration @ComponentScan(basePackages = "com.demo") public class CustomConfigApplication { public static void main(String[] args) { SpringApplication.run(CustomConfigApplication.class, args); } } |

4. @ComponentScan

定义 :指定 Spring 扫描组件的包路径(扫描 @Component、@Service、@Controller 等注解)。

作用 :替代 XML 中的 <context:component-scan>,手动指定扫描范围。

实用场景:组件不在主类同级 / 子包下时,需手动指定扫描路径。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @SpringBootApplication // 扫描 com.other 包下的所有组件 @ComponentScan(basePackages = {"com.demo", "com.other"}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } |

二、组件注册注解

1. @Component

定义:通用组件注解,标记类为 Spring 管理的 Bean。

作用:将普通类纳入 Spring IoC 容器管理,成为可依赖注入的 Bean。

实用场景:非分层(如工具类、通用组件)的普通类注册为 Bean。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.stereotype.Component; // 注册为 Spring Bean,默认名称为 "myUtils"(类名首字母小写) @Component public class MyUtils { public String format(String str) { return "[" + str + "]"; } } |

2. @Controller

定义 :MVC 控制器注解,继承 @Component。

作用:标记类为 Web 控制器,处理 HTTP 请求,返回视图或数据。

实用场景 :Spring MVC 接口层(传统视图返回或配合 @ResponseBody 返回 JSON)。

示例

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UserController { // 返回 JSON 数据(替代 @RestController) @GetMapping("/user") @ResponseBody public String getUser() { return "{'name':'张三'}"; } } |

3. @RestController

定义 :@Controller + @ResponseBody 的组合注解。

作用 :标记类为 REST 控制器,所有方法返回值直接转为 JSON/XML,无需手动加 @ResponseBody。

实用场景:前后端分离的接口开发(RESTful API)。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; // 所有方法默认返回 JSON @RestController public class OrderController { @GetMapping("/order") public Order getOrder() { Order order = new Order(); order.setId(1L); order.setName("手机"); return order; // 自动转为 JSON } // 内部静态类(仅示例用) static class Order { private Long id; private String name; // 省略 getter/setter } } |

4. @Service

定义 :业务层注解,继承 @Component。

作用:标记类为业务逻辑层 Bean,语义化区分分层。

实用场景:Service 层(业务逻辑处理)。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.stereotype.Service; @Service public class UserService { public String getUserInfo(Long id) { return "用户ID:" + id + ",名称:张三"; } } |

5. @Repository

定义 :数据访问层注解,继承 @Component。

作用:标记类为数据访问层(DAO)Bean,支持异常转译(Spring 自动将 JDBC/Hibernate 异常转为 Spring 统一的 DataAccessException)。

实用场景:DAO 层(数据库操作、持久化处理)。

示例

|------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.stereotype.Repository; @Repository public class UserRepository { public String findById(Long id) { return "从数据库查询用户:" + id; } } |

三、依赖注入注解

1. @Autowired

定义:自动依赖注入注解。

作用 :按类型自动注入 Spring 容器中的 Bean,可用于字段、构造方法、setter 方法。

实用场景:依赖注入(如 Service 注入 Repository、Controller 注入 Service)。

示例

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { // 字段注入(简单场景) @Autowired private UserService userService; // 构造方法注入(推荐,支持不可变对象) /* private final UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } */ @GetMapping("/user/info") public String getUserInfo(Long id) { return userService.getUserInfo(id); } } |

2. @Resource

定义:JDK 自带的依赖注入注解(JSR-250)。

作用 :默认按名称 注入,也可指定类型,弥补 @Autowired 仅按类型注入的不足。

实用场景:需要按名称注入多个同类型 Bean 时。

示例

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import javax.annotation.Resource; import org.springframework.web.bind.annotation.RestController; @RestController public class OrderController { // 按名称注入(指定 name 属性) @Resource(name = "taskExecutor") private ExecutorService executorService; // 省略业务方法 } |

3. @Qualifier

定义 :配合 @Autowired 使用,指定注入 Bean 的名称。

作用:解决同类型多个 Bean 时的注入歧义问题。

实用场景:同类型多个 Bean(如多个数据源、多个线程池)。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { // 按名称注入名为 "taskExecutor" 的 Bean @Autowired @Qualifier("taskExecutor") private ExecutorService executor; } |

四、请求处理注解(Web 层)

1. @RequestMapping

定义:映射 HTTP 请求到控制器方法。

作用:指定请求路径、请求方法(GET/POST 等)、请求参数、响应类型等。

实用场景:通用请求映射(可用于类 / 方法)。

示例

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController // 类级别映射:所有方法前缀为 /api @RequestMapping("/api") public class ApiController { // 方法级别映射:仅处理 GET 请求,路径为 /api/hello @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() { return "Hello Spring Boot"; } } |

2. @GetMapping / @PostMapping / @PutMapping / @DeleteMapping

定义 :@RequestMapping 的简化版,分别对应 GET/POST/PUT/DELETE 请求方法。

作用:简化请求方法配置,语义更清晰。

实用场景:RESTful API 开发(按 HTTP 方法区分增删改查)。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/users") public class UserRestController { // GET 请求:查询用户 @GetMapping("/{id}") public String getUser(@PathVariable Long id) { return "查询用户:" + id; } // POST 请求:创建用户 @PostMapping public String createUser(@RequestBody User user) { return "创建用户:" + user.getName(); } // PUT 请求:更新用户 @PutMapping("/{id}") public String updateUser(@PathVariable Long id, @RequestBody User user) { return "更新用户 " + id + ":" + user.getName(); } // DELETE 请求:删除用户 @DeleteMapping("/{id}") public String deleteUser(@PathVariable Long id) { return "删除用户:" + id; } static class User { private String name; // 省略 getter/setter } } |

3. @PathVariable

定义:绑定 URL 路径参数到方法参数。

作用 :获取 URL 中的动态参数(如 /users/{id} 中的 id)。

实用场景:RESTful API 中获取资源 ID。

示例 :见上方 @GetMapping("/{id}") 示例。

4. @RequestParam

定义:绑定 HTTP 请求参数到方法参数。

作用 :获取 URL 拼接参数(如 /users?name=张三)或表单参数。

实用场景:获取请求参数(支持必填、默认值配置)。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ParamController { // 获取 name 参数(非必填,默认值为 "未知") @GetMapping("/param") public String getParam(@RequestParam(value = "name", defaultValue = "未知") String name) { return "参数值:" + name; } } |

5. @RequestBody

定义:绑定 HTTP 请求体(JSON/XML)到方法参数。

作用:接收前端传递的 JSON 数据,自动转为 Java 对象。

实用场景:POST/PUT 请求中接收复杂参数(如创建 / 更新对象)。

示例 :见上方 @PostMapping 示例。

6. @RequestHeader

定义:绑定 HTTP 请求头到方法参数。

作用:获取请求头信息(如 Token、Content-Type)。

实用场景:鉴权(获取 Token)、解析请求头参数。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RestController; @RestController public class HeaderController { @GetMapping("/header") public String getHeader(@RequestHeader("Authorization") String token) { return "请求头 Token:" + token; } } |

五、配置读取注解

1. @Value

定义:读取配置文件(application.properties/yml)中的值并注入到字段 / 方法参数。

作用:简化配置读取,支持 SpEL 表达式。

实用场景:读取单个配置项(如端口、数据库地址)。

示例

|----------------------------------------------------------|
| # application.properties app.name=demo-app app.port=8080 |

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ConfigController { // 注入单个配置项 @Value("{app.name}") private String appName; // 注入配置项,指定默认值 @Value("{app.version:1.0.0}") private String appVersion; @GetMapping("/config") public String getConfig() { return "应用名称:" + appName + ",版本:" + appVersion; } } |

2. @ConfigurationProperties

定义:批量绑定配置文件中的属性到 Java 类。

作用 :替代多个 @Value,适合读取一组相关配置(如数据库、Redis 配置)。

实用场景:批量读取配置(如数据源配置、第三方服务配置)。

示例

|---------------------------------------------------------------------------------------------------------------------------------------------------|
| # application.properties spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 |

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; // 批量绑定以 spring.datasource 为前缀的配置 @Component @ConfigurationProperties(prefix = "spring.datasource") public class DataSourceProperties { private String url; private String username; private String password; // 省略 getter/setter @Override public String toString() { return "DataSourceProperties{" + "url='" + url + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } } |

3. @PropertySource

定义:加载自定义配置文件(非 application.properties/yml)。

作用:读取指定路径的配置文件(如 config/custom.properties)。

实用场景:配置文件拆分(如业务配置、第三方配置)。

示例

|-------------------------------------------------------------------------------|
| # custom.properties(resources/config 目录下) custom.key=123456 custom.desc=自定义配置 |

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Value; @Component // 加载自定义配置文件 @PropertySource("classpath:config/custom.properties") public class CustomConfig { @Value("{custom.key}") private String key; @Value("{custom.desc}") private String desc; // 省略 getter/setter } |

六、事务管理注解

1. @Transactional

定义:声明式事务注解,标记方法 / 类需要事务管理。

作用:自动管理事务(提交 / 回滚),支持配置隔离级别、传播行为等。

实用场景:数据库操作(增删改),保证数据一致性。

示例

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class OrderService { // 类级别:所有方法默认开启事务 // @Transactional // 方法级别:仅该方法开启事务,发生异常时回滚 @Transactional(rollbackFor = Exception.class) // 捕获所有异常回滚 public void createOrder(Order order) { // 1. 插入订单表 // 2. 更新库存表 // 若任意一步抛异常,事务回滚 } } |

七、条件注解(按需配置)

1. @ConditionalOnClass / @ConditionalOnMissingClass

定义:基于类路径是否存在指定类来决定是否加载配置。

作用:按需加载 Bean(如引入 Redis 依赖才加载 Redis 配置)。

实用场景:自定义 Starter、按需配置组件。

示例

|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import redis.clients.jedis.Jedis; // 仅当类路径存在 Jedis 类时,加载该配置 @Configuration @ConditionalOnClass(Jedis.class) public class RedisConfig { @Bean public Jedis jedis() { return new Jedis("localhost", 6379); } } |

2. @ConditionalOnProperty

定义:基于配置文件中的属性值决定是否加载配置。

作用:通过配置开关控制 Bean 是否生效。

实用场景:功能开关(如是否开启缓存、是否启用日志)。

示例

|-------------------------------------------------|
| # application.properties app.redis.enabled=true |

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration // 仅当 app.redis.enabled=true 时加载该配置 @ConditionalOnProperty(prefix = "app.redis", name = "enabled", havingValue = "true") public class RedisAutoConfig { // 省略 Bean 定义 } |

八、其他常用注解

1. @Bean

定义 :在配置类中声明 Bean,替代 XML 中的 <bean> 标签。

作用:将方法返回值注册为 Spring Bean,可指定名称、作用域。

实用场景:注册第三方组件(如线程池、数据源)、自定义 Bean。

示例 :见上方 @Configuration 中的 taskExecutor 示例。

2. @Scope

定义:指定 Bean 的作用域。

作用:控制 Bean 的创建模式(单例、原型等)。

实用场景:需要多实例 Bean 时(如原型模式)。

示例

|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; @Configuration public class ScopeConfig { // 原型模式:每次获取 Bean 都创建新实例 @Bean @Scope("prototype") public User user() { return new User(); } static class User {} } |

3. @Lazy

定义:延迟加载 Bean。

作用:Bean 不在启动时初始化,首次使用时才创建。

实用场景:重量级 Bean(如数据库连接池),减少启动时间。

示例

|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; @Configuration public class LazyConfig { @Bean @Lazy public HeavyService heavyService() { return new HeavyService(); } static class HeavyService {} } |

总结

核心注解 :@SpringBootApplication 是入口,@Configuration 用于配置类,@ComponentScan 控制组件扫描范围。

组件注册 :@Component 是通用注解,@Controller/@RestController(Web 层)、@Service(业务层)、@Repository(数据层)是语义化细分。

核心功能注解 :依赖注入用 @Autowired/@Resource/@Qualifier;请求处理用 @GetMapping/@PostMapping 等;配置读取用 @Value/@ConfigurationProperties;事务管理用 @Transactional。

以上是 Spring Boot 开发中最常用的注解集合,掌握这些注解能覆盖 90% 以上的开发场景,后续可根据具体需求(如缓存、异步、安全)扩展学习专项注解。

相关推荐
爱丽_2 小时前
AQS 原理主线:state、CLH 队列、独占/共享与实战排查
java·开发语言·jvm
帐篷Li2 小时前
Superpowers:让 AI 编程助手拥有专业级软件开发流程
人工智能·everything
明月照山海-2 小时前
机器学习周报三十七
人工智能·机器学习
TOWE technology2 小时前
从“制造”到“智造”:智能PDU如何成为智慧工厂的电力“神经中枢”
大数据·人工智能·制造·数据中心·电源管理·智能pdu
flying_13142 小时前
图神经网络分享系列-HAN(Heterogeneous Graph Attention Network)(一)
人工智能·深度学习·图神经网络·异构图·han·节点级注意力·语义级注意力
小江的记录本2 小时前
【Redis】Redis常用命令速查表(完整版)
java·前端·数据库·redis·后端·spring·缓存
卓怡学长2 小时前
m281基于SSM框架的电脑测评系统
java·数据库·spring·tomcat·maven·intellij-idea
MIka2 小时前
CopilotKit 入门:用 Runtime 和 React Core 搭建真正可用的 AI Copilot
人工智能·typescript·agent
一 铭2 小时前
Agent设计方式-工具调用:从自然语言到工具调用的桥梁
人工智能·大模型