Я работаю с yaml и spring boot, и я создам метод, который будет проверять мое поле.
Пример моего метода:
@PropertySource("classpath:defaultValue.yml")
public final class ValidateAttributeValue {
public static String validateAttributeValue(String attributeName, String attributeValue){
if (nonNull(attributeValue)){
return attributeValue;
}
//here I have to return default value from file based on attributeName
}
ямл-файл:
values:
field: defaultValue
field1: defaultValue1
field2: defaultValue2
field3: defaultValue3
Как это можно реализовать в Spring boot + yaml?
вы не можете получить доступ к файлу yml, используя @PropertySource
Вы можете использовать YamlPropertiesFactoryBean
для преобразования YAML в PropertySource.
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
// for ignoreResourceNotFound
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException)
throw (FileNotFoundException) e.getCause();
throw e;
}
}
}
А затем используйте его как:
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:blog.yaml")
public class YamlPropertysourceApplication {
Полное описание вы найдете здесь:
https://mdeinum.github.io/2018-07-04-PropertySource-with-yaml-files/
Вы можете автоматически подключить среду и получить к ней доступ, как показано, аналогично ответу на этот вопрос: stackoverflow.com/questions/23506471/…