【发布时间】:2020-04-27 16:29:25
【问题描述】:
我正在学习 Spring Boot,并且对参考文档中的一个示例有疑问。 documentation 的以下部分提及
6.使用@SpringBootApplication 注解
单个@SpringBootApplication 注解可用于启用这些 三个特点,即:
@EnableAutoConfiguration:启用 Spring Boot 的自动配置 机制
@ComponentScan:启用@Component 扫描所在的包 应用程序所在位置(请参阅最佳做法)
@Configuration:允许在上下文中注册额外的bean或导入 额外的配置类
以下示例用它启用的任何功能替换这个单个注释,这让我有点困惑。例子
package com.example.myapplication;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ MyConfig.class, MyAnotherConfig.class })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
示例说明
在这个例子中,Application 就像任何其他 Spring Boot 应用程序,除了 @Component 注释的类和 未检测到@ConfigurationProperties 注释的类 自动并且显式导入用户定义的 bean(请参阅 @导入)。
我在上面的示例代码中看到的唯一主要区别是它没有@ComponentScan 注释。我还在 SO answer 的 cmets 部分中读到(Stephane Nicoll 2017 年 5 月 5 日 11:07),不建议正式使用 @Component 注释来自动检测 @ConfigurationProperties。所以我的假设是带有@ConfigurationProperties 的Spring 框架类没有用@Component 注释。
我还检查了@SpringBootApplication 注释源,但无法识别任何可以自动检测@ConfigurationProperties 注释类的内容。
参考文档2.8.3. Enabling @ConfigurationProperties-annotated types 部分显示了以下扫描和自动检测@ConfigurationProperties 的方法
@SpringBootApplication
@ConfigurationPropertiesScan({ "com.example.app", "org.acme.another" })
public class MyApplication {
}
有了所有这些细节,我想了解
为什么在这个例子中明确提到 @ConfigurationProperties-annotated 类不会被自动检测到?以及使用@SpringBootApplication时如何自动检测@ConfigurationProperties注解的类。
附加说明:我发现文档的prior version 和current 之间存在细微差别。以下参考缺少当前参考
请记住,@EnableConfigurationProperties 注释是 还会自动应用于您的项目,以便任何现有的 bean 带有@ConfigurationProperties 注释的配置是从 环境
【问题讨论】:
标签: spring-boot component-scan