@EnableConfigurationProperties 不适用于 yaml 格式,但适用于点符号
@EnableConfigurationProperties does not work with yaml format but works with the dot notation
我正在尝试测试从我的 application.yml 文件到 POJO class 的简单 属性 绑定。当我使用点符号设置 属性 时,我可以让我的单元测试打印出 属性 值,但是当我将相同的 属性 更改为 .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());
}
}
进一步挖掘后,令人惊讶的是@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());
}
}
我正在尝试测试从我的 application.yml 文件到 POJO class 的简单 属性 绑定。当我使用点符号设置 属性 时,我可以让我的单元测试打印出 属性 值,但是当我将相同的 属性 更改为 .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());
}
}
进一步挖掘后,令人惊讶的是@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());
}
}