application.properties 未使用 @EnableAutoConfiguration 和自定义 spring 引导程序读取

application.properties not read with @EnableAutoConfiguration and custom spring boot starter

我尝试创建一个简单的自定义 spring 引导程序,它在 application.properties 中读取 属性 :

@EnableConfigurationProperties({ CustomStarterProperties.class })
@Configuration
public class CustomStarterAutoConfiguration {

    @Autowired
    private CustomStarterProperties properties;

    @Bean
    public String customStarterMessage() {
        return properties.getMessage();
    }
}

及其 ConfigurationProperties :

@ConfigurationProperties(prefix = "custom.starter")
public class CustomStarterProperties {

    private String message;

  /* getter and setter */
           ...
}

还有对应的application.propertiesMETA-INF/spring.factories来启用autoconfiguration

我有另一个项目将此 starter 声明为依赖项,我在其中编写了一个测试以查看是否创建了 customStarterMessage Bean:

@RunWith(SpringRunner.class)
@EnableAutoConfiguration
public class TotoTest {

    @Autowired
    String customStarterMessage;

    @Test
    public void loadContext() {
        assertThat(customStarterMessage).isNotNull();
    }
}

此测试失败(即使项目中有适当的 application.properties 文件)因为 application.properties 似乎未被读取。

它与 @SpringBootTest 注释而不是 @EnableAutoConfiguration 配合使用效果很好,但我想了解为什么 EnableAutoConfiguration 没有使用我的 application.properties 文件,而根据我的理解,所有 Spring 自动配置基于属性。

谢谢

@EnableAutoConfiguration 正在测试 类 没有为您准备所需的测试上下文。

@SpringBootTest 根据默认规范为您设置默认测试上下文,例如从根包扫描,从默认资源加载。要从不属于根包层次结构的自定义包加载,从您定义的自定义资源目录加载,即使在测试上下文配置中也是如此。您的所有配置将根据您定义的 @EnableAutoConfiguration 在您的实际启动项目中自动完成。