Spring Boot
application.yml
dependency injection
map configuration
YAML tutorial

Spring Boot - inject map from application.yml

Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD

Spring Boot is a powerful framework for building Java-based applications efficiently with minimal setup. One of the key features of Spring Boot is its support for externalized configuration, typically managed via application.yml or application.properties files. This article delves into how to inject a map defined in application.yml into a Spring Boot component or service, enhancing application configurability and manageability.

Understanding Configuration in Spring Boot

Spring Boot supports both .properties and .yml files for external configuration. application.yml is often preferred for complex hierarchical data configurations due to its concise and human-readable structure.

Why Use Maps in Configuration?

Maps are tremendously useful in configuration for:

  • Grouping related properties: Manage sets of related configurations as a single logical unit.
  • Scalability and organization: Easily scale configurations by simply adding key-value pairs.
  • Dynamic configurations: Facilitate dynamic key-value-based configurations without altering the code.

Defining a Map in application.yml

When you want to define a map in application.yml, the configuration syntax is straightforward. Here's how you can define a map:

yaml
1myapp:
2  settings:
3    feature-toggles:
4      feature1: true
5      feature2: false
6      feature3: true

In the snippet above, a nested map is defined under myapp.settings.feature-toggles, where each feature flag is a key-value pair.

Injecting the Map Using @ConfigurationProperties

The primary way to bind the YAML configuration to a Java class is through the @ConfigurationProperties annotation. It enables the binding of entire classes with prefixed properties.

Step 1: Define a Configuration Class

First, create a Java class that will hold this configuration:

java
1import org.springframework.boot.context.properties.ConfigurationProperties;
2import org.springframework.stereotype.Component;
3
4import java.util.Map;
5
6@Component
7@ConfigurationProperties(prefix = "myapp.settings")
8public class FeatureToggleProperties {
9  
10    private Map<String, Boolean> featureToggles;
11
12    public Map<String, Boolean> getFeatureToggles() {
13        return featureToggles;
14    }
15
16    public void setFeatureToggles(Map<String, Boolean> featureToggles) {
17        this.featureToggles = featureToggles;
18    }
19}

Step 2: Enable Configuration Properties Binding

The @EnableConfigurationProperties annotation is used to ensure that the @ConfigurationProperties beans are effectively managed by Spring Boot:

java
1import org.springframework.boot.context.properties.EnableConfigurationProperties;
2import org.springframework.context.annotation.Configuration;
3
4@Configuration
5@EnableConfigurationProperties(FeatureToggleProperties.class)
6public class AppConfig {
7}

Step 3: Using the Map in Application Components

Once your map is configured and injected into a @Component, you can utilize it in any Spring-managed component:

java
1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.stereotype.Service;
3
4@Service
5public class FeatureToggleService {
6
7    private final FeatureToggleProperties featureToggleProperties;
8
9    @Autowired
10    public FeatureToggleService(FeatureToggleProperties featureToggleProperties) {
11        this.featureToggleProperties = featureToggleProperties;
12    }
13
14    public boolean isFeatureEnabled(String feature) {
15        return featureToggleProperties.getFeatureToggles()
16                                      .getOrDefault(feature, false);
17    }
18}

In this service, you dynamically check if a feature is enabled based on the map injected from the configuration.

Key Points Summary

Here is a quick summary of the key points:

Key PointDescription
Configuration Fileapplication.yml is used for hierarchical configuration.
Define MapUse nested structures in YAML to define maps.
BindingsUse @ConfigurationProperties with a prefix to bind maps.
Enable BindingsUse @EnableConfigurationProperties to activate configuration property bindings.
Inject ConfigurationEasily inject configuration maps into services or components using Spring dependency injection.
Scalability and FlexibilityMaps offer scalable and flexible configuration handling.

Additional Considerations

  • Validation: Consider using JSR-303 annotations for validating configuration properties. For instance, @NotEmpty can ensure properties are not undefined.
  • Profiles: Spring profiles allow managing differing configurations for environments (e.g., application-dev.yml, application-prod.yml).
  • Lombok: Consider using Lombok’s @Data or @Getter/@Setter annotations to reduce boilerplate in configuration classes.
  • Testing: Utilize property-based tests to ensure configurations meet expected criteria. Mock configurations if necessary for isolated tests.

Injecting maps from application.yml provides a powerful and flexible mechanism for managing dynamic application configurations in a Spring Boot application. This modular approach allows developers to maintain clean codebases with external configurations driving application logic.


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.

Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD

All Rights Reserved.