spring Spring在没有@Autowired注解的构造函数中注入依赖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41092751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:17:00  来源:igfitidea点击:

Spring injects dependencies in constructor without @Autowired annotation

springspring-bootdependency-injectionautowired

提问by winter

I'm experimenting with examples from this official Spring tutorialsand there is a dependency on this code:
https://github.com/spring-guides/gs-async-method/tree/master/complete

我正在尝试使用这个官方 Spring教程中的示例,并且依赖于此代码:https:
//github.com/spring-guides/gs-async-method/tree/master/complete

If you look at the code on AppRunner.javaclass, I have 2 questions:

如果您查看AppRunner.java课堂上的代码,我有两个问题:

  1. When server is starting, if I put a breakpoint in this class's constructor, seems like in the constructor, the GitHubLookupServiceis provided by spring, using the @Servicebean that was configured. BUT, there was no @Autowiredannotation on the constructor, so how in the world this constructor get called with the right dependency? It was supposed to be null.
  1. 当服务器启动时,如果我在这个类的构造函数中放置一个断点,看起来就像在构造函数中一样,GitHubLookupService由 spring 提供,使用@Service配置的bean。但是,@Autowired构造函数上没有注释,那么这个构造函数到底是如何被调用的?它应该是null

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 Frameworkor Spring boot?
Am I missing something?

它是Spring Boot的自动假设吗?
Spring 是否看到“私有字段 + 构造函数参数,并假设它应该寻找合适的 bean?
它是Spring Framework还是Spring boot
我错过了什么吗?

  1. As I remember, it was mendatory to provide default constructorto 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?
  1. 我记得,必须为beans/service 等提供默认构造函数。为什么这个类 ( AppRunner) 没有默认构造函数?Spring 如何知道它应该使用参数运行构造函数?是因为它是唯一的构造函数吗?

回答by dunni

Starting with Spring 4.3, if a class, which is configured as a Spring bean, has only one constructor, the @Autowiredannotation can be omitted and Spring will use that constructor and inject all necessary dependencies.

从 Spring 4.3开始,如果配置为 Spring bean 的类只有一个构造函数,则@Autowired可以省略注释,Spring 将使用该构造函数并注入所有必要的依赖项。

Regarding the default constructor: You either need the default constructor, a constructor with the @Autowiredannotation when you have multiple constructors, or only one constructor in your class with or without the @Autowiredannotation.

关于默认构造函数@Autowired当您有多个构造函数时,您要么需要默认构造函数,一个带有注释的构造函数,要么在您的类中只需要一个带有或不带有@Autowired注释的构造函数。

Read the @Autowiredchapter from the official Spring documentation for more information.

阅读@Autowired官方 Spring 文档中的章节以获取更多信息。