【问题标题】:Can't pass in YAML Values using Spring无法使用 Spring 传入 YAML 值
【发布时间】:2015-09-04 10:26:51
【问题描述】:

我有一个如下所示的 config.yml 文件

---
name:
  archive:
    documentfiles:
      username: rafa
      password: hello

我的配置是这样的

@ConfigurationProperties(prefix = "name")
public class YamlConfig {

    private List<String> servers = new ArrayList<String>();

    public List<String> getServers() {
        return this.servers;
    }
}

在我的测试类中,我尝试从返回的列表中获取第一个值,但它返回一个 IndexOutOfBoundsException,所以我知道 config.yml 值没有传入。有人可以提供一些帮助吗?下面是我的测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationConfiguration.class})
public class OfflineFileViewerResourceTest {
     @Test
    public void password(){
        fileViewer = new OfflineFileViewerResource();
        YamlConfig yaml = new YamlConfig();
        List<String> list = yaml.getServers();

        assertEquals("archive", list.get(0));


    }
}

【问题讨论】:

    标签: java spring testing yaml


    【解决方案1】:

    当您手动创建 bean(使用 new)时,任何 Spring 注释(例如 @ConfigurationProperties)都将不起作用:

    YamlConfig yaml = new YamlConfig();
    

    要完成您的需要,您应该允许 Spring 管理 bean 并将它们从 ApplicationContext 注入到您的测试中。

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      相关资源
      最近更新 更多