0
0
Spring Bootframework~5 mins

Why configuration matters in Spring Boot

Choose your learning style9 modes available
Introduction

Configuration helps your Spring Boot app work correctly in different places without changing code. It makes your app flexible and easier to manage.

You want to change database settings without rewriting code.
You need to set different values for development and production environments.
You want to enable or disable features easily.
You need to adjust app behavior based on user location or preferences.
Syntax
Spring Boot
springboot-app/src/main/resources/application.properties

# Example configuration
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
featureX.enabled=true
Use application.properties or application.yml files to store configuration.
Spring Boot automatically loads these files when the app starts.
Examples
You can use either .properties or .yml files for configuration.
Spring Boot
# application.properties
server.port=8081

# application.yml
server:
  port: 8081
Turn features on or off by changing configuration values.
Spring Boot
# Enable a feature
featureX.enabled=true
Use profiles to have different settings for development and production.
Spring Boot
# Different config for dev and prod
# application-dev.properties
server.port=8082

# application-prod.properties
server.port=80
Sample Program

This Spring Boot app reads a configuration value featureX.enabled. It shows how configuration controls app behavior without changing code.

Spring Boot
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@RestController
class HelloController {

    @Value("${featureX.enabled:false}")
    private boolean featureXEnabled;

    @GetMapping("/feature-status")
    public String featureStatus() {
        if (featureXEnabled) {
            return "Feature X is enabled";
        } else {
            return "Feature X is disabled";
        }
    }
}
OutputSuccess
Important Notes

Always keep sensitive info like passwords out of public config files.

Use profiles to separate settings for different environments.

Summary

Configuration lets you change app behavior without code changes.

Spring Boot loads config files automatically at startup.

Use profiles to manage settings for different environments easily.