Spring Boot 常用注解详解

📝 Spring Boot 常用注解详解


1️⃣ 组件声明类注解

@Component

  • 通用组件,交由 IoC 容器管理。
java 复制代码
@Component
public class MyComponent {}

@Service

  • 用于业务逻辑层,语义更明确。
java 复制代码
@Service
public class UserService {}

@Repository

  • 用于数据访问层,额外支持 Spring 异常转换。
java 复制代码
@Repository
public class UserRepository {}

@Controller & @RestController

  • @Controller 用于页面返回(模板渲染)。
  • @RestController = @Controller + @ResponseBody,用于返回 JSON。
java 复制代码
@RestController
@RequestMapping("/api")
public class UserController {
    @GetMapping("/hello")
    public String hello() { return "hello"; }
}

2️⃣ 配置类相关

@Configuration

  • 声明配置类,作用类似 XML <beans>。
java 复制代码
@Configuration
public class MyConfig {
    @Bean
    public SAXReader saxReader(DeptService deptService) {
        return new SAXReader();
    }
}

@Bean

  • 方法返回值作为 Bean 注册到容器。

  • 常用属性:

    • name / value:指定 Bean 名称,默认方法名。
    • initMethod:初始化方法。
    • destroyMethod:销毁方法。
java 复制代码
@Bean(name = "customReader", initMethod = "init", destroyMethod = "destroy")
public SAXReader reader() {
    return new SAXReader();
}

@Import

  • 引入外部配置类或 ImportSelector。
java 复制代码
@Configuration
@Import(MyConfig.class)
public class MainConfig {}

3️⃣ 属性绑定

@ConfigurationProperties(prefix = "aliyun.oss")

  • 将配置文件中的 aliyun.oss.* 属性绑定到 Java Bean。
  • 要求类有 getter/setter。
yaml 复制代码
aliyun:
  oss:
    endpoint: oss-cn-hangzhou.aliyuncs.com
    accessKeyId: myId
java 复制代码
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class OssProperties {
    private String endpoint;
    private String accessKeyId;
}

@EnableConfigurationProperties

  • 作用 :启用 @ConfigurationProperties 标注的配置类,使其生效并注入 IoC 容器。
  • 如果配置类已经加了 @Component,通常不需要。
  • 但如果配置类本身不是 Spring Bean(没加 @Component),必须通过该注解启用。
java 复制代码
@ConfigurationProperties(prefix = "aliyun.oss")
public class OssProperties { ... }

@SpringBootApplication
@EnableConfigurationProperties(OssProperties.class)
public class MyApplication {}

4️⃣ 条件装配(Spring Boot 自动配置常用)

@ConditionalOnProperty

  • 当配置文件中存在指定属性和值时,才加载 Bean。
java 复制代码
@Bean
@ConditionalOnProperty(name = "feature.switch", havingValue = "true")
public Feature feature() { return new Feature(); }

@ConditionalOnClass

  • 当类路径下存在指定类时才加载 Bean。
java 复制代码
@Bean
@ConditionalOnClass(name = "io.jsonwebtoken.Jwts")
public JwtService jwtService() { return new JwtService(); }

@ConditionalOnMissingBean

  • 当容器中没有某个 Bean 时才加载。
java 复制代码
@Bean
@ConditionalOnMissingBean(DeptService.class)
public DeptService deptService() { return new DeptServiceImpl(); }

5️⃣ 自定义注解

元注解

  • @Retention(RetentionPolicy.RUNTIME):运行时可用。
  • @Target(ElementType.TYPE):可用于类/接口。
  • @Documented:生成文档包含注解。
  • @Inherited:子类继承父类注解。

示例:自定义启用注解

java 复制代码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(MyImportSelector.class)
public @interface EnableHeaderConfig {}

使用:

java 复制代码
@SpringBootApplication
@EnableHeaderConfig
public class MyApp {}

6️⃣ 启动与扫描

@SpringBootApplication

组合注解,包含:

  • @SpringBootConfiguration(= @Configuration)
  • @EnableAutoConfiguration(开启自动配置)
  • @ComponentScan(扫描当前包及子包的 Bean)
java 复制代码
@SpringBootApplication(scanBasePackages = {"com.itheima","com.example"})
public class MyApplication {}

@ComponentScan

  • 自定义扫描路径。
java 复制代码
@ComponentScan(basePackages = {"com.itheima", "com.example"})

7️⃣ Web 层映射注解

  • @RequestMapping:通用请求映射。
  • @GetMapping / @PostMapping / @PutMapping / @DeleteMapping。
  • @PathVariable:路径变量。
  • @RequestParam:请求参数。
  • @RequestBody:请求体 JSON → Java 对象。
java 复制代码
@RestController
@RequestMapping("/dept")
public class DeptController {
    @GetMapping("/{id}")
    public String get(@PathVariable Integer id) {
        return "Dept:" + id;
    }
}

8️⃣ 依赖注入

  • @Autowired:按类型注入。
  • @Qualifier:指定 Bean 名称。
  • @Value("${server.port}"):注入配置属性。
java 复制代码
@Autowired
private DeptService deptService;

@Value("${server.port}")
private int port;

9️⃣ 事务与 AOP

@Transactional

声明事务。

java 复制代码
@Transactional
public void save() { ... }

AOP 切面

java 复制代码
@Aspect
@Component
public class LogAspect {
    @Before("execution(* com.itheima.service.*.*(..))")
    public void log() { System.out.println("method called"); }
}

✅ 总结表

分类 注解 常见参数/说明
核心组件 @Component / @Service / @Repository / @Controller / @RestController 声明 Bean
配置类 @Configuration / @Bean name/initMethod/destroyMethod
属性绑定 @ConfigurationProperties / @EnableConfigurationProperties 批量配置绑定
导入 @Import 导入配置类/选择器
条件装配 @ConditionalOnProperty / @ConditionalOnClass / @ConditionalOnMissingBean 控制 Bean 生效条件
自定义注解 @Retention / @Target / @Import 自定义开关注解
启动类 @SpringBootApplication / @ComponentScan 启动配置、扫描
Web 层 @RequestMapping / @GetMapping / @PathVariable / @RequestParam / @RequestBody Web 请求映射
依赖注入 @Autowired / @Qualifier / @Value Bean & 配置注入
事务与 AOP @Transactional / @Aspect 声明式事务 & 切面

🧩

复制代码
Spring Boot 注解体系
│
├── 核心组件
│   ├── @Component / @Service / @Repository
│   └── @Controller / @RestController
│
├── 配置类
│   ├── @Configuration
│   ├── @Bean (name, initMethod, destroyMethod)
│   ├── @Import
│   └── @EnableConfigurationProperties
│
├── 属性绑定
│   └── @ConfigurationProperties(prefix="xxx")
│
├── 条件装配
│   ├── @ConditionalOnProperty
│   ├── @ConditionalOnClass
│   └── @ConditionalOnMissingBean
│
├── 启动与扫描
│   ├── @SpringBootApplication
│   └── @ComponentScan
│
├── Web 层映射
│   ├── @RequestMapping
│   ├── @GetMapping / @PostMapping
│   ├── @PathVariable / @RequestParam
│   └── @RequestBody
│
├── 依赖注入
│   ├── @Autowired
│   ├── @Qualifier
│   └── @Value
│
├── 事务与 AOP
│   ├── @Transactional
│   └── @Aspect (@Before/@After/@Around)
│
└── 自定义注解
    ├── @Retention / @Target
    └── @Import(ImportSelector)

相关推荐
子兮曰5 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰5 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
默_笙5 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
爱勇宝5 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
qq_426003965 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫5 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
胡写代码5 天前
别再前后端各写一套表单校验了
java·后端
长沙三为智能科技5 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
大勇前进5 天前
原生 PHP 还是 Laravel?小项目到底要不要上框架
后端