我正在学习 Spring Boot,并且对参考文档中的一个示例有疑问。文档的以下部分提到
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-annotated 类和 @ConfigurationProperties-annotated 类, 并且显式导入用户定义的 beans(请参阅@Import)。
我在上面的示例代码中看到的唯一主要区别是它没有@ComponentScan
注释。我还在 SO答案的评论部分(Stephane Nicoll 2017 年 5 月 5 日 11:07)读到 @Component 注释不建议正式自动检测 @ConfigurationProperties。所以我的假设是带有@ConfigurationProperties 的Spring 框架类没有用@Component 注释。
我还检查了@SpringBootApplication
注释源,无法识别任何应该启用自动检测带@ConfigurationProperties
注释的类的东西。
参考文件2.8.3。启用@ConfigurationProperties-annotated types部分显示以下扫描和自动检测@ConfigurationProperties 的方法
@SpringBootApplication
@ConfigurationPropertiesScan({ "com.example.app", "org.acme.another" })
public class MyApplication {
}
有了所有这些细节,我想了解
为什么在此示例中明确提到@ConfigurationProperties 注释的类不会自动检测到?以及使用@SpringBootApplication 时如何自动检测@ConfigurationProperties 注释类。
附加说明:我发现文档的先前版本与当前版本之间存在细微差别。以下参考缺少当前参考
请记住,@EnableConfigurationProperties 注释也会自动应用于您的项目,以便从环境中配置任何使用 @ConfigurationProperties 注释的现有 bean