为什么 Spring 的构造器注入不需要 @Autowired 注解?
Spring的三种注入方式
在讨论这个问题之前,我们可以先来回忆一下Spring的依赖注入的三种方式。
分别是——属性注入、setter 注入、构造器注入
一、属性注入
这种方式是最常用的,我们可以使用 @Autowired 或者是 @Resource 进行注入
@RestController
@RequestMapping("/shop")
public class ShopController {
@Resource
public IShopService shopService;
/**
* 根据id查询商铺信息
* @param id 商铺id
* @return 商铺详情数据
*/
@GetMapping("/{id}")
public Result queryShopById(@PathVariable("id") Long id) {
//return Result.ok(shopService.getById(id));
return shopService.queryById(id);
}
}
使用方式是最简单,但是也是最不推荐的!要使用也是推荐使用 @Resource!
二、setter 注入
这种方法是 Spring3.X 版本比较推荐的,但是我基本上没有见到有人用过!
@Controller
public class DemoController {
private DemoService demoService;
@Autowired
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
}
三、构造器注入
这就是目前 Spring 最为推荐的注入方式,直接通过带参构造方法来注入。
// 部分代码
@Component
public class RedisIdWorker {
private StringRedisTemplate stringRedisTemplate;
public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
}
为什么 Spring的构造器注入不需要 @Autowired 注解?
As of Spring Framework 4.3, an
@Autowired
annotation on such a constructor is no longer necessary if the target bean only defines one constructor to begin with. However, if several constructors are available, at least one must be annotated to teach the container which one to use.
这是 Spring 框架自身的一个特性,对于一个 SpringBean 来说,如果其只有一个构造方法,那么 Spring 会使用该构造方法并自动注入其所需要的全部依赖!
官网解释如下
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)