1

我正在学习 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

4

1 回答 1

2

以下是我从分析中了解到的。

@ConfigurationProperties带注释的类型可以通过以下方式注册到 ApplicationContext

  1. 使用属于( 等)@ConfigurationProperties范围内的注释来注释类。根据 Stephane Nicoll 的评论,不推荐,这对我来说很有意义。@ComponentScan@Component@Service

  2. 使用注释 @EnableConfigurationProperties。为此,使用注释的类应该使用属于(等)@EnableConfigurationProperties 范围的注释进行注释 @ComponentScan@Component@Service

  3. 使用注释@ConfigurationPropertiesScan并确保使用注释的类@ConfigurationProperties位于其雷达之下。用法类似于@ComponentScan

现在,当我们用@SpringBootApplication它启用和省略的单个注释替换@ComponentScan(如示例)时,@EnableConfigurationProperties注册类型的方式(第 2 点)@ConfigurationProperties将不起作用。这可能回答了我关于为什么和如何的问题。

明确提到这一点可能是因为和之间的联系@EnableConfigurationProperties对于@ComponentScan像我这样的人来说并不那么明显。

额外细节。

@ConfigurationProperties我们使用时注解类型的注册是通过注解导入@EnableConfigurationProperties的类发生的EnableConfigurationPropertiesRegistrar

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(EnableConfigurationPropertiesRegistrar.class)
public @interface EnableConfigurationProperties {..}
于 2020-01-11T03:17:16.507 回答