Spring在没有@Autowired注解的情况下将依赖项注入构造函数中 [英] Spring injects dependencies in constructor without @Autowired annotation
问题描述
我正在尝试使用此官方Spring的示例教程,其中有一个依赖于此代码:
https://github.com/spring-guides/gs-async -method/tree/master/complete
I'm experimenting with examples from this official Spring tutorials and there is a dependency on this code:
https://github.com/spring-guides/gs-async-method/tree/master/complete
如果您查看AppRunner.java
类上的代码,我有2个问题:
If you look at the code on AppRunner.java
class, I have 2 questions:
- 服务器启动时,如果我在此类的构造函数中放置一个断点,就像在构造函数中一样,
GitHubLookupService
由spring使用配置的@Service
bean提供.但是,构造函数上没有@Autowired
批注,那么该构造函数在世界范围内如何以正确的依赖关系进行调用?应该是null
.
- When server is starting, if I put a breakpoint in this class's constructor, seems like in the constructor, the
GitHubLookupService
is provided by spring, using the@Service
bean that was configured. BUT, there was no@Autowired
annotation on the constructor, so how in the world this constructor get called with the right dependency? It was supposed to benull
.
这是 Spring Boot 的自动假设吗?
Spring是否看到私有字段+构造函数参数",并且假定它应该寻找合适的bean?
是 Spring Framework 还是 Spring boot ?
我想念什么吗?
Is it an automatic assumption of Spring Boot?
Does Spring see "private field + constructor argument, and it assumes it should look for an appropriate bean?
Is it Spring Framework or Spring boot?
Am I missing something?
- 我记得,必须为bean/服务等提供默认构造函数.此类(
AppRunner
)为何没有默认构造函数? Spring如何知道应该使用参数运行构造函数? 是因为它是唯一的构造函数吗?
- As I remember, it was mendatory to provide default constructor to beans / service etc. How come this class (
AppRunner
) doesn't have a default constructor? How does Spring knows that it should run the constructor with the argument? Is it because it is the only constructor?
推荐答案
从Spring 4.3 开始,如果配置为Spring bean的类只有一个构造函数,则@Autowired
注解可以省略,Spring将使用该构造函数并注入所有必要的依赖项.
Starting with Spring 4.3, if a class, which is configured as a Spring bean, has only one constructor, the @Autowired
annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
关于默认构造函数:您需要默认构造函数,如果您有多个构造函数,则需要带有@Autowired
批注的构造函数,或者您的类中只有一个构造函数,带有或不带有@Autowired
注释.
Regarding the default constructor: You either need the default constructor, a constructor with the @Autowired
annotation when you have multiple constructors, or only one constructor in your class with or without the @Autowired
annotation.
阅读 <有关更多信息,请参见Spring官方文档中的c3> 章节.
这篇关于Spring在没有@Autowired注解的情况下将依赖项注入构造函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!