Spring Framework
PropertySource
YAML
Configuration
Java

Spring PropertySource using YAML

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Spring Framework is a comprehensive framework for enterprise-grade Java applications. One of its powerful features is the capability to externalize configuration properties, which allows developers to manage different environments more efficiently. Spring's support for properties is primarily facilitated through the @PropertySource annotation, which can import properties from a variety of sources, including YAML files.

Understanding @PropertySource

@PropertySource is an annotation used to read properties from a properties file within a Spring context. Traditionally, it works with .properties files, but with the addition of Spring Boot and enhanced YAML support, YAML files can also serve as a source for configuration properties when used in conjunction with Spring's Environment and PropertySources.

YAML in Spring

YAML (YAML Ain't Markup Language) is a human-readable data serialization standard that is commonly used for configuration files. It's often favored over .properties files due to its readability and ability to format complex data hierarchically.

In a Spring Boot context, YAML files are natively supported as they are part of the application's property sources defined in application.yaml or application.yml.

Setting Up YAML Properties

A sample application.yaml might look like this:

yaml
1server:
2  port: 8080
3app:
4  name: "SpringPropertiesDemo"
5  features:
6    enable: true
7    version: 1.0

These properties allow for an elegant and structured definition of configuration properties. Each property can be accessed through Spring's @Value annotation or Environment.

Using @PropertySource with YAML

While @PropertySource typically deals with properties files, you can still read YAML content by properly leveraging Spring's built-in facilities.

1. Spring Boot Application Configuration

In Spring Boot, the framework automatically reads application.yaml or application.yml at startup. Therefore, you usually don't need @PropertySource to read from YAML if you're working within a Spring Boot application.

2. Custom YAML Files

For non-standard YAML files, you can use a utility method to load YAML into a Properties object:

java
1@Configuration
2public class CustomPropertyConfig {
3
4    @Bean
5    public static PropertySourcesPlaceholderConfigurer properties() {
6        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
7        yaml.setResources(new ClassPathResource("custom-config.yaml"));
8
9        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
10        configurer.setProperties(yaml.getObject());
11        return configurer;
12    }
13}

This example uses YamlPropertiesFactoryBean to convert YAML into Properties, which Spring can then interpret using its standard mechanisms. You can then use @Value to inject these properties.

Accessing YAML Properties

With properties loaded, you can access them using:

  • @Value Annotation: To access specific properties, you can use the @Value annotation:
java
    @Value("${app.name}")
    private String appName;
  • Environment Interface: The Environment interface can be injected to access properties:
java
1    @Autowired
2    private Environment env;
3
4    public void accessProperties() {
5        String appName = env.getProperty("app.name");
6    }

Validating Properties

Spring provides a way to validate configuration properties using @Validated and JSR-303/JSR-380 validation constraints:

java
1@ConfigurationProperties(prefix = "app")
2@Validated
3public class AppProperties {
4
5    @NotNull
6    private String name;
7
8    @NotNull
9    private FeatureProperties features;
10
11    // getters and setters
12
13    public static class FeatureProperties {
14        private boolean enable;
15        private double version;
16        
17        // getters and setters
18    }
19}

To activate configuration properties, use:

java
1@EnableConfigurationProperties(AppProperties.class)
2public class AppConfig {
3    // Config
4}

Summary Table

FeatureDescription
File TypeYAML files (application.yaml)
Access Methods@Value, Environment
Custom File InclusionYamlPropertiesFactoryBean to convert YAML to Properties
Automatic SupportNative support from Spring Boot
Property ValidationUse @Validated with validation constraints
Structured Data HandlingYAML supports hierarchical property data
Use CaseIdeal for configurations requiring readable and structured data

Conclusion

While @PropertySource facilitates reading properties from standard .properties files, YAML's flexibility demands a slightly different approach. By leveraging YamlPropertiesFactoryBean and Spring Boot's native support, developers can smoothly integrate YAML into their Spring applications, benefiting from a readable and structured way to manage application configurations. This approach, combined with property validation and dynamic injection, makes YAML a robust choice in the modern Spring developer's toolkit.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.