Spring中两种Constructor注入写法的差异及最佳实践探讨
Spring构造注入两种@Autowired写法的区别与最佳实践
先看你给出的两种写法:
写法一:@Autowired标注在构造方法参数上
@Component public class MyService { private final MyRepository myRepository; public MyService(@Autowired MyRepository myRepository) { this.myRepository = myRepository; } // 其他代码 }
写法二:@Autowired标注在构造方法上
@Component public class MyService { private final MyRepository myRepository; @Autowired public MyService(MyRepository myRepository) { this.myRepository = myRepository; } // 其他代码 }
两者的区别
在Spring 4.3及以上版本中,针对只有单个构造方法的@Component标注类,这两种写法的功能完全等价——Spring都会正确识别并完成MyRepository的依赖注入。
细微差异仅在多构造方法场景下体现:
- 若
@Autowired标注在参数上,Spring会尝试寻找包含该参数的构造方法注入,但这种用法极少,可读性较差。 - 若
@Autowired标注在构造方法上,Spring会明确优先选择该构造方法创建Bean,这是多构造方法场景下的标准用法。
最佳实践
- 优先省略@Autowired:Spring 4.3+之后,只要类只有一个构造方法且被Spring管理(比如加了
@Component或其他 stereotype 注解),Spring会自动完成构造注入,无需写任何@Autowired,这是最简洁的写法:@Component public class MyService { private final MyRepository myRepository; public MyService(MyRepository myRepository) { this.myRepository = myRepository; } // 其他代码 } - 如果必须显式写
@Autowired(比如兼容旧版本Spring、符合团队编码规范),优先标注在构造方法上,能更清晰地表明整个构造方法用于依赖注入,尤其是多参数场景下,比逐个标记参数更简洁易读。
内容的提问来源于stack exchange,提问作者java12399900
相关产品推荐
相关产品推荐

