Introduction

Spring Boot provides a flexible and convenient way to configure your application using properties and YAML files. This allows you to externalize configuration and make your application more maintainable. In this guide, we'll explore how to configure Spring Boot properties and YAML files with sample code.


Prerequisites

Before you start, make sure you have the following prerequisites:


Using Properties Files

Properties files are a simple way to configure your Spring Boot application. You can use them to set key-value pairs for your application's properties. Let's create an example properties file:

# application.properties
# Database Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
# Server Configuration
server.port=8080

In this example, we set properties for the database connection and server port. You can access these properties in your application by using the @Value annotation:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Value("${spring.datasource.url}")
private String databaseUrl;
@Value("${server.port}")
private int serverPort;
}

Using YAML Files

YAML files provide a more human-readable and structured way to configure your Spring Boot application. Let's create an example YAML file:

# application.yml
# Database Configuration
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: secret
# Server Configuration
server:
port: 8080

In this YAML example, we define the same properties as in the properties file. To access these properties, you can use the @Value annotation as before.


Using Profiles

Spring Boot allows you to use profiles to manage different sets of configurations for different environments. You can define profiles in your properties or YAML files. For example:

# application.yml
# Common Configuration
spring:
datasource:
url: jdbc:mysql://localhost:3306/commondb
username: commonuser
password: commonpass
# Development Profile
---
spring:
profiles: development
datasource:
url: jdbc:mysql://localhost:3306/devdb
username: devuser
password: devpass
# Production Profile
---
spring:
profiles: production
datasource:
url: jdbc:mysql://localhost:3306/proddb
username: produser
password: prodpass

In this example, we have a common configuration and separate configurations for development and production profiles. You can activate a profile by setting the spring.profiles.active property in your properties file or YAML file.


Conclusion

Configuring Spring Boot properties and YAML files is a crucial part of application development. It allows you to keep configuration separate from your code, making your application more adaptable and maintainable. With profiles, you can manage different configurations for various environments efficiently.