Spring常用注解总结#
一句话答案#
核心注解:@Component/@Service/@Repository(Bean 注册)、@Autowired(注入)、@Transactional(事务)、@Configuration+@Bean(配置)。
核心要点
1. Bean 注册#
| 注解 | 作用 |
|---|---|
@Component | 通用组件,组件扫描自动注册 |
@Service / @Controller | @Component 的语义化派生,标业务层 / Web 层 |
@Repository | 数据访问层;配合 PersistenceExceptionTranslationPostProcessor 把底层持久化异常转成 Spring 的 DataAccessException |
@RestController | @Controller + @ResponseBody |
@ComponentScan | 指定扫描包 |
@Scope / @Lazy / @Primary | 作用域 / 懒加载 / 同类型多个 Bean 时优先注入 |
2. 依赖注入#
| 注解 | 来源 | 默认匹配方式 |
|---|---|---|
@Autowired | Spring | 按类型;多个候选时配 @Qualifier 或 @Primary,再退回按字段/参数名匹配 |
@Qualifier | Spring | 按 Bean 名称限定 |
@Resource | Jakarta(Spring 6 / Boot 3 起是 jakarta.annotation.Resource,原 javax.annotation) | 先按名称,找不到再按类型 |
@Value | Spring | 注入配置值 ${...} 或 SpEL #{...} |
单构造器的类可省略 @Autowired(Spring 4.3 起),官方推荐构造器注入。
3. 配置类#
| 注解 | 作用 |
|---|---|
@Configuration | 配置类;默认 proxyBeanMethods = true(Full 模式),CGLIB 代理保证 @Bean 方法互调返回同一单例 |
@Bean | 方法返回值注册为 Bean,常用于第三方类 |
@Import | 导入配置类 / ImportSelector / ImportBeanDefinitionRegistrar |
@Conditional 系列 | 按条件注册(Spring Boot 的 @ConditionalOnClass、@ConditionalOnMissingBean 等) |
@PropertySource / @ConfigurationProperties | 加载配置文件 / 把配置批量绑定到对象 |
4. Web(Spring MVC)#
@RequestMapping 及 @GetMapping/@PostMapping 等、@PathVariable、@RequestParam、@RequestBody、@ResponseBody、@RestControllerAdvice + @ExceptionHandler(全局异常处理)。
5. 基于 AOP 的功能注解#
@Transactional(事务)、@Async(异步,需 @EnableAsync)、@Cacheable(缓存,需 @EnableCaching)、@Scheduled(定时任务,需 @EnableScheduling)。前三个靠代理实现,同类自调用都会失效。
6. Spring Boot#
@SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan。
连带考点:字段注入的循环依赖#
单例 Bean 的字段/setter 注入循环依赖由三级缓存(singletonObjects / earlySingletonObjects / singletonFactories)解决,构造器注入和 prototype 的循环依赖解决不了;Spring Boot 2.6 起默认禁止循环引用(spring.main.allow-circular-references=false),需要显式开启。细节见 循环依赖与三级缓存。
面试回答(2分钟版)
Spring常用注解可以分三组来记。第一组是Bean注册:@Component是通用注解,@Service、@Repository、@Controller是它的语义化派生,功能相同但表达不同的架构层次,@Repository额外提供数据访问异常转换。第二组是依赖注入:@Autowired按类型注入,存在多个同类型Bean时配合@Qualifier按名称指定;@Resource是JSR-250标准注解(Spring 6起是jakarta包),默认按名称注入。第三组是配置类:@Configuration标注配置类,内部@Bean方法手动注册第三方库的类,@Configuration保证@Bean方法之间互相调用返回的是同一个单例,不加只是lite模式不保证单例。另外循环依赖是高频追问:Spring通过三级缓存解决Singleton Bean的字段注入循环依赖,一级缓存存完整Bean,二级存早期引用,三级存ObjectFactory延迟创建AOP代理。但构造器注入的循环依赖和Prototype Bean的循环依赖无法解决,而且Spring Boot 2.6起默认禁止循环引用,需要显式开启。
追问与易错
追问方向:
- “@Component 和 @Bean 区别?”→ @Component 标注在类上由组件扫描自动注册,适合自己写的类;@Bean 标注在方法上手动创建实例注册,适合第三方库的类(无法加注解)
- “@Autowired 和 @Resource 区别?”→ @Autowired 是 Spring 注解默认按类型(byType)注入,类型冲突配合 @Qualifier;@Resource 是 JSR-250 标准注解默认按名称(byName)注入,更具可移植性
- “@Configuration 和 @Component 区别?”→ @Configuration 类中 @Bean 方法互相调用时返回同一个单例实例(Full 模式,通过 CGLIB 代理拦截);@Component 类中 @Bean 方法互相调用会创建新实例(Lite 模式,不保证单例)
易错点:
- ❌ @Component/@Service/@Repository 完全一样——语义不同
- ❌ @Configuration 不加也行——lite mode 不保证 @Bean 单例