是否有從yaml
文件中的特定對象的貨清單的任何簡單的方法。因此,例如我有yaml
文件,配置這樣的:彈簧載荷YAML列表值
list:
-
name: a
url: a.com
-
name: b
url: b.com
,我想從這個屬性來創建List<Endpoints>
。我知道它非常容易使用的彈簧引導和@ConfigurationProperties
註釋做的,但我可以做到這一點使用怎麼只是春天?
是否有從yaml
文件中的特定對象的貨清單的任何簡單的方法。因此,例如我有yaml
文件,配置這樣的:彈簧載荷YAML列表值
list:
-
name: a
url: a.com
-
name: b
url: b.com
,我想從這個屬性來創建List<Endpoints>
。我知道它非常容易使用的彈簧引導和@ConfigurationProperties
註釋做的,但我可以做到這一點使用怎麼只是春天?
這個怎麼樣。
YML文件
list: 'a,a.com;b,b.com'
組件類
@Value("#{T(org.blah.spring.service.Endpoint).getEndpoints('${list}'.split(';'))}")
List<Endpoint> endpoints;
和端點
@Getter
@Setter
@AllArgsConstructor
public class Endpoint {
private String name;
private String url;
public static List<Endpoint> getEndpoints(List<String> strings){
List<Endpoint> endpoints = Lists.newArrayList();
for(String s: strings){
String split[] = s.split(",");
endpoints.add(new Endpoint(split[0], split[1]));
}
return endpoints;
}
}
忽略我的回答如果你正在尋找一個免費的開機解決方案(如果你正在建設圖書館)。
隨着PropertiesConfigurationFactory
,YamlPropertySourceLoader
和你可以讀一個Yaml
文件到一個POJO:
import org.junit.Test;
import org.springframework.boot.bind.PropertiesConfigurationFactory;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.io.ByteArrayResource;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class YamlTest {
private static final String YAML_STRING = "list: \n" +
" - \n" +
" name: a \n" +
" url: a.com \n" +
" - \n" +
" name: b \n" +
" url: b.com";
@Test
public void shouldLoadYamlIntoObject() throws Exception {
PropertiesConfigurationFactory<EndpointsHolder> propertiesConfigurationFactory = new PropertiesConfigurationFactory<>(EndpointsHolder.class);
MutablePropertySources propertySources = new MutablePropertySources();
YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
propertySources.addFirst(yamlPropertySourceLoader.load("list", new ByteArrayResource(YAML_STRING.getBytes()), null));
propertiesConfigurationFactory.setPropertySources(propertySources);
EndpointsHolder actual = propertiesConfigurationFactory.getObject();
assertTrue(actual.getList().get(0).getName().equals("a"));
assertTrue(actual.getList().get(1).getUrl().equals("b.com"));
}
public static class EndpointsHolder {
List<Endpoints> list;
public List<Endpoints> getList() {
return list;
}
public void setList(List<Endpoints> list) {
this.list = list;
}
}
public static class Endpoints {
String name;
String url;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
只需更換new ByteArrayResource(YAML_STRING.getBytes())
用你自己的數據源。