📝 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)