【问题标题】:application.properties not read with @EnableAutoConfiguration and custom spring boot starterapplication.properties 不使用@EnableAutoConfiguration 和自定义spring boot starter 读取
【发布时间】:2020-02-25 20:03:11
【问题描述】:

我尝试创建一个简单的自定义 Spring Boot 启动器,它读取 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

我有另一个项目将这个启动器声明为依赖项,我在其中编写了一个测试来查看是否创建了 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 AutoConfiguration 都是基于属性的。

谢谢

【问题讨论】:

  • 你使用不同的包名吗?如果您包含的依赖项具有不同的包,除了您在第二个项目中的包之外,您还需要为依赖项中的包添加@ComponentScan
  • 谢谢@AndreiSfat!我已经尝试使用正确的包声明 @ComponentScan 但它不起作用:(

标签: spring-boot properties spring-boot-starter


【解决方案1】:

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

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

【讨论】:

  • 谢谢@ScanQR!我通过在我的测试类中添加@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class) 使其工作。
  • @matdan 当然。如果您发现答案有用,请接受它。谢谢!
猜你喜欢
  • 2019-03-15
  • 1970-01-01
  • 2020-10-19
  • 2018-09-15
  • 1970-01-01
  • 2019-10-28
  • 2015-11-10
  • 2018-01-07
  • 1970-01-01
相关资源
最近更新 更多