Spring在没有@Autowired注解的构造函数中注入依赖 [英] Spring injects dependencies in constructor without @Autowired annotation
问题描述
我正在尝试使用这个官方 Spring 教程 中的示例,并且有一个对这段代码的依赖:
https://github.com/spring-guides/gs-async-方法/树/主/完成
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
类上的代码,我有两个问题:
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 框架 还是 Spring 启动?
我错过了什么吗?
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.
阅读@Autowired
来自官方 Spring 文档的章节以获取更多信息.
Read the @Autowired
chapter from the official Spring documentation for more information.
这篇关于Spring在没有@Autowired注解的构造函数中注入依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!