Usama Nadeem
Usama Nadeem

Reputation: 89

How to use YAML files using Spring Framework?

My application is spring based, and I would like to load yml file from a centralized server, but the unable to do so.

My yml file is like this:

spring:
  application:
    name: signed-in-web
  cloud:
    config:
      uri: ${server.url}
health:
  config:
    enabled: false

note: server.url is defined in vm options. I had checked from rest client that properties are valid and available on the server.

Then I tried to copy it on a property file like this: application.properties

LOCATION_SEARCH=${properties.app.api-key.location-search}

I had java configuration class like this:

@Profile("!test")
@ComponentScan(basePackages = { "com.company.frontend.*" })
@Configuration
@PropertySource("classpath:properties/qa_env.properties")
public class propertiesConfig {

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

I supposed that this will load the configuration like this:

@Value("${LOCATION_SEARCH}")
public static String LOCATION_SEARCH;

but I am getting null. Somehow I am not been able to find where the problem is. Will

Upvotes: 2

Views: 2807

Answers (1)

OrangeDog
OrangeDog

Reputation: 38787

If you're using Spring Boot you just need to call it application-qa.yaml and enable the qa profile. See also spring.config and spring.profiles in Common Application Properties.

Otherwise you just need to declare the yaml file in @PropertySource or @PropertySources.

Only if you don't want the properties in the global environment do you start needing to use PropertiesConfigurationFactory and YamlPropertiesFactoryBean to manually bind them.

Upvotes: 1

Related Questions