ROB*_*ail 5 java spring dependency-injection
我知道使用 Spring 有 3 种方法进行依赖注入:字段注入、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;
}
}
Run Code Online (Sandbox Code Playgroud)
可以这么说,哪一个优先?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'
Run Code Online (Sandbox Code Playgroud)
话虽这么说,以下情况将按顺序发生:
FortuneService,因为需要先构造该对象,然后才能发生其他事情。@Autowired实例注释的字段FortuneService@Autowired它将调用带有实例注释的方法FortuneService现在,根据 的范围FortuneService,它将注入一个单例(默认)或创建一个新实例(当 bean 处于原型范围时)。
注意:顺序可以从的来源AutowiredAnnotationBeanPostProcessor推断出来。调用构造函数是合乎逻辑的,但字段与方法的顺序来自方法buildAutowiringMetadata。它首先检测字段,然后检测方法。
| 归档时间: |
|
| 查看次数: |
1987 次 |
| 最近记录: |