我有一个使用此构建器构建的 YAML 配置。构建器接受一个 InputStream,它允许我使用测试配置文件对其进行测试。它很好用,因为 SnakeYAML 可以弄清楚如何构建我的对象。
public static MyConfig buildFromYaml(InputStream is) {
MyConfig config = null;
Yaml yaml = new Yaml();
try{
config = yaml.loadAs(is, MyConfig.class);
} catch (Exception e) {
e.printStackTrace();
}
return config;
}
但是在我的应用程序中,它恰好是一个 Cucumber Runner,这个配置需要被构造函数注入到使用它的对象中,这恰好由 PicoContainer 完成。
public MyStepDefinition(MyConfig myConfig, OtherAppStuff otherAppStuff) {
otherAppStuff.doStuffWith(myConfig);
}
所以现在我需要一个 MyConfig 的构造函数,以便 MyConfig 可以由 PicoContainer 构造,然后注入到 MyStepDefinition 中。
我想出的是这个,这是不对的。
public class MyConfig {
public List<ConfigItem> configItemList;
public MyConfig() {
InputStream is = getClass().getResourceAsStream("/myconfigdefinition.yaml");
MyConfig myConfig = buildFromYaml(is);
this.configItemList = myConfig.configItemList;
}
public static MyConfig buildFromYaml(InputStream is) {
...
}
}
问题是构造函数调用 buildFromYaml 的无限循环,它再次调用构造函数并因此循环。
所以总结一下,我的问题是,我如何编写一个使用构建器的构造器来构建正在构建的类?也就是说,在MyConfig的构造函数中
如何使用?yaml.loadAs(is, MyConfig.class)