Spring Boot allows us to configure application properties in two formats that are application.properties
and application.yml
. Both serve the same purpose of configuring application settings such as database connections, server ports, and framework-specific configurations. Many developers prefer YAML (.yml
) due to its human-readable format and better support for complex configurations.
In this article, we will learn how to convert application.properties to application.yml and implement a simple project using yaml file.
Converting application.properties to application.yml in Spring Boot
Spring Boot uses configuration files like application.properties
or application.yml
to set up application-wide settings such as database connections, server ports, security credentials, and other framework-specific configurations. Both formats externalize the application properties, allowing for flexible deployment and easier environment-based configuration.
Difference Between application.properties and application.yml
application.properties
This file uses a simple, flat format where properties are defined as key-value pairs. Properties are typically represented in dot-separated notation, which can become cumbersome and less readable for complex configurations.
Example in application.properties
:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=rootpass
application.yml
YAML (YAML Ain't Markup Language) represents data in a hierarchical structure using indentation. YAML is often preferred for its cleaner syntax, especially when dealing with nested configurations like lists, maps, or objects.
Example of the same properties in YAML:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: rootpass
Hierarchical Structure and Nesting in YAML
YAML provides a nested, hierarchical structure. This allows related configuration settings to be grouped logically. Instead of using dot notation, YAML leverages indentation to represent the hierarchy.
Example of Grouping Nested Properties:
In application.properties
:
server.port=8080
management.endpoints.web.exposure.include=*
management.endpoints.web.base-path=/actuator
Converted to the application.yml, these settings are grouped into a clear hierarchy:
server:
port: 8080
management:
endpoints:
web:
exposure:
include: "*"
base-path: /actuator
Explanation:
- The root-level key server has the sub-key with the value of the 8080.
- Similarly, the management section has multiple sub keys under the endpoints, making it clear that web, exposure, and base-path are all the part of the management settings.
This structured format in the YAML makes the configurations easier to read and manage, especially when there are many nested properties.
Handling Arrays and Lists in YAML
YAML offers native support for arrays and lists, which can be tricky in application.properties
. In YAML, lists are denoted with dashes (-
).
Example:
In application.properties
, lists are typically defined as comma-separated strings:
app.allowed-origins=http://example.com/,http://example2.com/
Converted to YAML:
app:
allowed-origins:
- http://example.com/
- http://example2.com/
The list format in the YAML is much cleaner, easier to the understand, and more intuitive when you need to make modifications.
Handling Maps and Complex Objects
YAML excels in handling complex objects or maps of key-value pairs. Representing these in application.properties
requires flattening the hierarchy into dot-separated keys, which can be confusing.
Example:
Suppose you need to define the complex configuration for the mail server, such as the connection settings, credientials, and properties. In the application.properties, it would be written as:
mail.server.host=smtp.example.com
mail.server.port=587
[email protected]
mail.server.password=secret
mail.server.properties.mail.smtp.auth=true
mail.server.properties.mail.smtp.starttls.enable=true
In YAML, it can be converted into the structure format that is easier to the read and manage:
mail:
server:
host: smtp.example.com
port: 587
username: [email protected]
password: secret
properties:
mail:
smtp:
auth: true
starttls:
enable: true
This hierarchical approach in the YAML makes it clear how the various settings relate to the each other, reducing the complexity and improving the maintainability.
Profile-Specific Configuration in YAML
Spring Boot supports environment-specific configurations using profiles, separated into files like application-dev.properties
, application-prod.properties
, etc. YAML simplifies this by allowing you to define multiple profiles in a single application.yml
file using the ---
syntax.
Example:
We can define the different configurations for the development and production environments in the one YAML file:
# Default settings
server:
port: 8080
# Development profile
---
spring:
profiles: dev
server:
port: 8081
# Production profile
---
spring:
profiles: prod
server:
port: 9090
In this example, the server.port value changes depending on the whether the dev or prod profile active. YAML can ability to manage the multiple profiles in the single file simplifies the profile management.
Error Prevention and Maintainability
Due to its indentation-based structure, YAML naturally groups related settings together, reducing the redundancy and making it harder to the accidentally misplace or mistype the key. It can be especially beneficial in the large projects with many configurations.
For example, the misaligned key in the application.properties might go unnoticed, but YAML's structure will immediately show it something is out of the place due to improper indentation.
Comparison Example:
In the application.properties, it can be easy to accidentally miss the structure:
management.endpoints.web.exposure.include=*
server.port=8080
management.endpoints.web.base-path=/actuator
But in the YAML, it would be harder to the misconfigure since all the management settings are grouped logically:
server:
port: 8080
management:
endpoints:
web:
exposure:
include: "*"
base-path: /actuator
Default Behavior in the Spring Boot
Spring Boot automatically detects and supports the both application.properties and application.yml without additional configuration. If both the files are present, Spring Boot will give the preference to the application.yml, but both files can coexist if needed.
Implementation of Spring Boot with application.yml
Configuration
Step 1: Create a New Spring Boot Project
Create a new Spring Boot project in IntelliJ IDEA.
Choose the following options:
- Name:
spring-boot-yaml-example
- Language:
Java
- Type:
Maven
- Packaging:
Jar
Click Next and Finish.
Step 2: Add Dependencies
Add the following dependencies into the Spring Boot project.
- Spring Web
- Spring Boot DevTools
- Lombok
- MySQL Driver
- Spring Data JPA
Click on the Create button.
Project Structure
After project creation done, the folder structure will look like the below image:
Step 3: Configure application.yml
Open the application.properties file rename into the application.yml and add the following server port, MySQL and hibernate configuration of the Spring Boot project. In this example, we will configure:
- A MySQL database connection
- Server properties like port and context path
- Logging properties
server:
port: 8080
servlet:
context-path: /api
spring:
datasource:
url: jdbc:mysql://localhost:3306/testdb
username: root
password: mypassword
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
database-platform: org.hibernate.dialect.MySQLDialect
logging:
level:
root: info
com.example: debug
- Server properties: The application will run on the port 8080 and use the /api context path.
- Database properties: The data sources connects to the local MySQL instance (testdb), with the user root and password password.
- Logging: Root level can be set to the info, while the package com.gfg is set to the debug.
Step 4: Create the HelloController Class
Create the simple REST controller to the verify the application runs correctly.
Java
package com.gfg.springbootyamlexample;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
// Endpoint to return a welcome message
@GetMapping("/hello")
public String sayHello() {
return "Hello, Welcome to the Spring Boot YAML example!";
}
}
A simple REST controller that handles GET
requests to /hello
and returns a welcome message.
Step 5: Main Class
This is the entry point of the application. There is no changes are required in the main class.
Java
package com.gfg.springbootyamlexample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootYamlExampleApplication {
// Entry point of the Spring Boot application
public static void main(String[] args) {
SpringApplication.run(SpringBootYamlExampleApplication.class, args);
}
}
pom.xml File:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg</groupId>
<artifactId>spring-boot-yaml-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-yaml-example</name>
<description>spring-boot-yaml-example</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 6: Run the Application
Run the application, and it will start on port 8080.
Step 7: Testing the Application
Make a GET
request to:
http://localhost:8080/api/hello
We should see the following message:
This project demonstrates a simple project setup using the application.yml to configure server properties, database connections, and logging, showing how easily complex configurations can be managed with the YAML.
Advantages of using the application.yml
- Readability: YAML’s hierarchical structure makes complex configurations easier to read and manage.
- Maintainability: Grouping related properties avoids configuration sprawl.
- Profiles: Managing multiple environments becomes easier with YAML's built-in profile support.
Use Cases
- Microservices Configuration: In distributed systems, YAML can often preferred for the organizing the environment-specific configurations in the microservices.
- Database Configurations: It can ideal for the configuring data sources with nested properties (like credentials, URLs, and driver names).
- Logging Setup: YAML's clear structures is help in configuring the different logging levels for the packages and classes.
Conclusion
Switching from application.properties to the application.yml in the Spring Boot offers the several advantages in the terms of readability and maintainability. YAML's hierarchical nature makes it easier to the manage complex configurations, especially when dealing with microservices or large projects. However, it can be essential to ensure the proper indentation when using the YAML, as formatting issues can lead to the runtime errors.
Both application.properties and application.yml are supported by the Spring Boot, so the choice depends on the projects complexity and developer preferences.