java - 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'
解决方案
首先,不要做那样的事情。
话虽如此,以下将按顺序发生:
- 它将使用 的实例调用构造函数
FortuneService
,因为需要先构造对象,然后才能发生其他任何事情。 - 它将注入
@Autowired
带有实例注释的字段FortuneService
- 它将调用
@Autowired
带有实例注释的方法FortuneService
现在根据 的范围FortuneService
,它将注入一个单例(默认)或创建一个新实例(当 bean 是原型范围时)。
注意:排序可以从. AutowiredAnnotationBeanPostProcessor
调用构造函数是合乎逻辑的,但字段与方法的顺序来自buildAutowiringMetadata
方法。它首先检测字段,然后检测方法。
推荐阅读
- amazon-web-services - 在 aws ec2 实例上设置 kubernetes 集群时,salt-master not working yet 错误
- docker - Docker Compose:使用 mysql:8 的 SpringBoot 应用程序
- json - 根据Postgres中的整数值查询json列
- java - 无法在通过单击应用程序中的链接打开的浏览器中找到元素
- node.js - sequelize datatypes.NOW 函数不生成时间戳
- eclipse - Eclipse“保存服务器项信息”
- c# - 使用SqlKata在sql中按月份名称分组
- apache-kafka - KAFKA 分区数据实现每日数据
- r - glm - R 中的异常值检测和删除
- dart - Flutter 中的特殊字符