@enableconfigurationproperties不适用于yaml格式,但适用于点表示法

1bqhqjot  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(428)

我正在尝试测试从application.yml文件到pojo类的简单属性绑定。我可以让我的单元测试打印出属性值,当我使用点符号设置属性时,但是当我将相同的属性更改为.yml表示时,我的单元测试打印出一个空值。我是不是漏了什么?


# this works

blah.resourcePrefix=blah

# this does not work

blah:
  resourcePrefix: blah
@ConfigurationProperties(prefix = "blah")
public class JustTesting {

    private String resourcePrefix;

    public String getResourcePrefix() {
        return resourcePrefix;
    }
    public void setResourcePrefix(String resourcePrefix) {
        this.resourcePrefix = resourcePrefix;
    }
}
@ExtendWith(SpringExtension.class)
@EnableConfigurationProperties(value = JustTesting.class)
@TestPropertySource("classpath:application.yml")
public class PropertiesTest {

    @Autowired
    JustTesting justTesting;

    @Test
    public void testProperties(){        
        System.out.println(justTesting.getResourcePrefix());
    }
}
5anewei6

5anewei61#

在进一步挖掘之后,令人惊讶的是@testpropertysource不支持.yml文件。baeldung有一篇很好的文章描述了如何添加这个功能。
https://www.baeldung.com/spring-yaml-propertysource
我走了一条稍微不同的路线,最终也为我工作,并像这样更新了我的单元测试注解。这样,我的application.yml文件就可以在不指定其位置的情况下被提取。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = JustTesting.class)
@EnableConfigurationProperties(value = JustTesting.class)
public class PropertiesTest {

    @Autowired
    JustTesting justTesting;

    @Test
    public void testProperties(){        
        System.out.println(justTesting.getResourcePrefix());        
    }
}

相关问题