【问题标题】:@EnableConfigurationProperties does not work with yaml format but works with the dot notation@EnableConfigurationProperties 不适用于 yaml 格式,但适用于点表示法
【发布时间】:2021-03-17 00:13:56
【问题描述】:

我正在尝试测试从我的 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());
    }
}

【问题讨论】:

    标签: java spring properties


    【解决方案1】:

    经过进一步挖掘,令人惊讶的是,@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());        
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多