PropertySource - Neethahiremath/Wiki GitHub Wiki
refer https://www.baeldung.com/spring-yaml-propertysource
use YamlPropertySourceFactory to custom the file reads
use YamlPropertySourceLoader for reading file and loading to PropertySource
@Configuration
@Component
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {
public YamlPropertySourceFactory() {
}
public PropertySource createPropertySource(String name, EncodedResource resource) throws IOException {
List<PropertySource<?>> propertySourceList = new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource());
return !propertySourceList.isEmpty() ? propertySourceList.iterator().next() : super.createPropertySource(name, resource);
}
and use it with Configuration
@PropertySource(value = "file:${Path}", factory = YamlPropertySourceFactory.class)
@Configuration
@ConfigurationProperties("read")
yml:
Path: /x/y/z
we can use YamlPropertiesFactoryBean to read yml files to Property and create PropertySource
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath: config/${file.config}.yml")
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException
{
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, factory.getObject());
}
reading from secret vault path:
@Getter
@Setter
@ToString
@Configuration
@ConditionalOnExpression("${val.enabled:false}")
@PropertySource(value = "${secrets.filePath}", factory = YamlPropertySourceFactory.class)
public class Config {
@Value("${key}")
private String key;
}
@Slf4j
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)
{
log.error(e.getMessage());
throw (FileNotFoundException) e.getCause();
}
else
{
log.error(e.getMessage());
throw e;
}
}
}
}
yml file mention the file path:
secrets: filePath: file:///etc/config/secrets