Raghuveer
Raghuveer

Reputation: 3057

YAML configuration in spring-core

Is there a way to use YAML configuration without spring boot. From docs its clear it may not be possible but experts may have other opinions.

Upvotes: 2

Views: 591

Answers (1)

hovanessyan
hovanessyan

Reputation: 31423

Yes there is a way. You need to use YamlPropertiesFactoryBean which is capable of reading/parsing yaml files.

You need this dependency on the classpath:

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.20</version>
</dependency>

Next you can load the properties from the yaml file and inject them into a PropertySourcesPlaceholderConfigurer using the getObject() method of YamlPropertiesFactoryBean which returns an instance of java.util.Properties

@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
  PropertySourcesPlaceholderConfigurer propertyConfigurer = new PropertySourcesPlaceholderConfigurer();
  YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
  yaml.setResources(new ClassPathResource("application.yml"));
  propertyConfigurer.setProperties(yaml.getObject());
  return propertyConfigurer;
}

You can then inject the properties from the yaml file using @Value for exmple.

Upvotes: 2

Related Questions