天天看点

为什么 Spring 的构造器注入不需要 @Autowired 注解?Spring的三种注入方式 

Spring的三种注入方式 

在讨论这个问题之前,我们可以先来回忆一下Spring的依赖注入的三种方式。

分别是——属性注入、setter 注入、构造器注入

为什么 Spring 的构造器注入不需要 @Autowired 注解?Spring的三种注入方式 

一、属性注入

这种方式是最常用的,我们可以使用 @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 会使用该构造方法并自动注入其所需要的全部依赖!

官网解释如下

Spring Framework Reference Documentation

为什么 Spring 的构造器注入不需要 @Autowired 注解?Spring的三种注入方式 

https://docs.spring.io/spring-framework/docs/4.3.x/spring-framework-reference/htmlsingle/#beans-autowired-annotation