首页 > 解决方案 > Spring - 依赖注入 - 哪个优先?

问题描述

我知道有 3 种方法可以使用 Spring 进行依赖注入:字段、setter 和构造函数注入。

但是假设我们在同一个组件中有更多的 3 个,如下所示:

import base.service.FortuneService;

@Component
public class FootballCoach implements Coach {
    
    //Field Injection
    @Autowired
    private FortuneService fortuneService;
    
    //setter Injection
    @Autowired
    public void setFortuneService(FortuneService fortuneService) {
        this.fortuneService = fortuneService;
    }
    //constructor Injection
    @Autowired
    public FootballCoach(FortuneService fortuneService) {
        this.fortuneService = fortuneService;
    }
}

哪个优先 - 可以这么说?Spring会只做所有3个并覆盖该fortuneService字段两次吗?如果是这样,最后一个站着的是哪一个?还是只会选择一个依赖注入?

我运行上面的代码没有问题,我得到了以下日志,但我真的不知道如何阅读它们。

注意:FortuneService是一个接口,我有一个HappyFortuneService实现它的类。

Sep 10, 2020 11:40:44 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry getSingleton
FINE: Creating shared instance of singleton bean 'footballCoach'
Sep 10, 2020 11:40:44 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry getSingleton
FINE: Creating shared instance of singleton bean 'happyFortuneService'
Sep 10, 2020 11:40:44 AM org.springframework.beans.factory.support.ConstructorResolver createArgumentArray
FINE: Autowiring by type from bean name 'footballCoach' via constructor to bean named 'happyFortuneService'
Sep 10, 2020 11:40:44 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry getSingleton
FINE: Creating shared instance of singleton bean 'tennisCoach'
Sep 10, 2020 11:40:44 AM org.springframework.beans.factory.support.ConstructorResolver createArgumentArray
FINE: Autowiring by type from bean name 'tennisCoach' via constructor to bean named 'happyFortuneService'

标签: javaspringdependency-injection

解决方案


首先,不要做那样的事情。

话虽如此,以下将按顺序发生:

  1. 它将使用 的实例调用构造函数FortuneService,因为需要先构造对象,然后才能发生其他任何事情。
  2. 它将注入@Autowired带有实例注释的字段FortuneService
  3. 它将调用@Autowired带有实例注释的方法FortuneService

现在根据 的范围FortuneService,它将注入一个单例(默认)或创建一个新实例(当 bean 是原型范围时)。

注意:排序可以. AutowiredAnnotationBeanPostProcessor调用构造函数是合乎逻辑的,但字段与方法的顺序来自buildAutowiringMetadata方法。它首先检测字段,然后检测方法。


推荐阅读