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)

相关推荐
用户4099322502122 小时前
PostgreSQL数据类型怎么选才高效不踩坑?
后端·ai编程·trae
GHOME2 小时前
MCP-学习(1)
前端·后端·mcp
fliter2 小时前
迈向易用的Rust
后端
起风了___2 小时前
Python 自动化下载夸克网盘分享文件:基于 Playwright 的完整实现(含登录态持久化与提取码处理)
后端·python
福大大架构师每日一题2 小时前
2025-09-27:子字符串连接后的最长回文串Ⅰ。用go语言,给定两个字符串 s 和 t。你可以从 s 中截取一段连续字符(也可以不取,即空串),再从 t 中
后端
麦兜*2 小时前
Redis 7.0 新特性深度解读:迈向生产级的新纪元
java·数据库·spring boot·redis·spring·spring cloud·缓存
我是华为OD~HR~栗栗呀2 小时前
测试转C++开发面经(华为OD)
java·c++·后端·python·华为od·华为·面试
龙茶清欢2 小时前
最新版 springdoc-openapi-starter-webmvc-ui 常用注解详解 + 实战示例
java·spring boot·ui·spring cloud