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)

相关推荐
野犬寒鸦30 分钟前
从零起步学习并发编程 || 第一章:初步认识进程与线程
java·服务器·后端·学习
Stream_Silver32 分钟前
【Agent学习笔记3:使用Python开发简单MCP服务】
笔记·python
我爱娃哈哈34 分钟前
SpringBoot + Flowable + 自定义节点:可视化工作流引擎,支持请假、报销、审批全场景
java·spring boot·后端
穿过锁扣的风36 分钟前
零基础入门 Python 爬虫:从基础到实战,爬取虎扑 / 豆瓣 / 图片全掌握
开发语言·爬虫·python
Stream_Silver40 分钟前
【Agent学习笔记2:深入理解Function Calling技术:从原理到实践】
笔记·python
love530love1 小时前
技术复盘:llama-cpp-python CUDA 编译实战 (Windows)
人工智能·windows·python·llama·aitechlab·cpp-python·cuda版本
韩师学子--小倪1 小时前
SpringBoot 优雅停服
spring boot·tomcat
逄逄不是胖胖2 小时前
《动手学深度学习》-60translate实现
人工智能·python·深度学习
橘颂TA2 小时前
【测试】自动化测试函数介绍——web 测试
python·功能测试·selenium·测试工具·dubbo
爱学习的阿磊2 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python