Tutoriel Spring Config Server - Microservices

Spring Config Server avec 3 Microservices

implémenter Spring Cloud Config Server avec des microservices A, B et C

Introduction

Qu'est-ce que Spring Cloud Config Server ?

Spring Cloud Config Server est un service qui centralise la gestion de la configuration de tous vos microservices. Imaginez-le comme une bibliothèque où chaque microservice vient chercher ses paramètres de configuration au démarrage.

Avantages principaux :

  • Centralisation : Toutes les configurations au même endroit
  • Séparation : Code et configuration séparés
  • Environnements : Configurations différentes pour dev, test, prod
  • Sécurité : Secrets chiffrés et sécurisés
graph TD A[Microservice A] --> B[Config Server] C[Microservice B] --> B D[Microservice C] --> B E[EurekaServer] --> B F[API Gateway] --> B B --> E[(Fichiers de Configuration)] style B fill:#4CAF50,stroke:#388E3C style E fill:#2196F3,stroke:#0D47A1 style A fill:#FF9800,stroke:#E65100 style C fill:#FF9800,stroke:#E65100 style D fill:#FF9800,stroke:#E65100

Architecture Globale Détaillée

graph TD B[Spring Config Server] B --> C[(Configuration Store)] C --> D[Local File System .properties] C --> E[Git Repository .properties] B --> F[Service A] B --> G[Service B] B --> H[Service C] B --> I[EurekaServer] B --> J[GateWay] style B fill:#4CAF50,stroke:#388E3C style C fill:#2196F3,stroke:#0D47A1 style F fill:#FF9800,stroke:#E65100 style G fill:#FF9800,stroke:#E65100 style H fill:#FF9800,stroke:#E65100

Cas d'Utilisation 1 : Configuration Locale avec .properties

1 Créer le projet Config Server

Utilisez Spring Initializr (https://start.spring.io) pour créer le projet :

  • Project : Maven Project
  • Language : Java
  • Spring Boot : 2.7.x ou supérieur
  • Dependencies : Spring Web, Config Server,actuator,devtools
  • Artifact : config-server

Fichier pom.xml du Config Server :


    <dependencies>
        <!-- Dépendance principale pour Config Server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
        
        <!-- Pour exposer les endpoints web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
   

2 Configuration du Config Server avec .properties

Fichier application.properties du Config Server :

# Port du serveur Config Server
spring.application.name=config-server4
server.port=8888
# Activation du profil natif pour configuration locale
spring.profiles.active=native

# Chemin vers les fichiers de configuration locaux
spring.cloud.config.server.native.searchLocations=file:///C:/Users/HP/Desktop/Projectsjeem/config-server4/config-repo

Structure du dépôt config-repo

config-repo/
├── application.properties      # Configuration commune
├── service-a.properties        # Configuration Service A
├── service-b.properties        # Configuration Service B
└── service-c.properties        # Configuration Service C

Explication détaillée des propriétés :

  • server.port=8888 : Le port 8888 est conventionnel pour Config Server
  • spring.profiles.active=native : Mode local (pas de Git)
  • spring.cloud.config.server.native.searchLocations : Où trouver les fichiers
  • logging.level.org.springframework.cloud=DEBUG : Logs détaillés pour débogage

3 Classe principale du Config Server

package com.example.configserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

/**
 * Classe principale du Config Server
 * 
 * @EnableConfigServer : Active les fonctionnalités de Config Server
 * Cette annotation transforme l'application en serveur de configuration
 */
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

Comprendre les annotations

  • @SpringBootApplication : Combine plusieurs annotations Spring importantes
  • @EnableConfigServer : Transforme l'application en Config Server
  • SpringApplication.run() : Démarre l'application Spring Boot

4 Créer les fichiers de configuration .properties

Créez le répertoire src/main/resources/config-repo et ajoutez les fichiers suivants :

Fichier application.properties (configuration commune à tous les services) :

# Configuration commune à tous les microservices
app.name=Microservices Application
app.version=1.0.0
app.environment=development

# Configuration des logs
logging.level.root=INFO
logging.level.com.example=DEBUG

# Exposition des endpoints de monitoring
management.endpoints.web.exposure.include=*

# Paramètres de base de données communs
database.driver=org.h2.Driver
database.dialect=org.hibernate.dialect.H2Dialect

Fichier service-a.properties :

# Configuration spécifique au Service A
eureka.client.service-url.defaultZone=http://localhost:8768/eureka/
server.port=8085
a=hello
app.mavariable=21212

#other configurations

# Informations du service
app.service.name=Service A
app.service.description=Premier microservice de l'application
app.service.version=1.0.0

# Fonctionnalités activées
app.features=feature1,feature2,feature3

# Configuration de la base de données
database.url=jdbc:h2:mem:servicea
database.username=sa
database.password=password

# Configuration API externe
external.api.url=https://api.servicea.com
external.api.timeout=5000
external.api.retries=3

# Paramètres de cache
cache.enabled=true
cache.ttl=300

Fichier service-b.properties :

# Configuration spécifique au Service B
eureka.client.service-url.defaultZone=http://localhost:8768/eureka/
server.port=8082


#other configurations

# Informations du service
app.service.name=Service B
app.service.description=Service d'authentification et de gestion des utilisateurs
app.service.version=1.0.0

# Fonctionnalités de sécurité
app.features=authentication,authorization,user-management

# Configuration de la base de données PostgreSQL
database.url=jdbc:postgresql://localhost:5432/serviceb
database.username=serviceb_user
database.password=secret_password
database.pool.size=10

# Configuration de sécurité JWT
security.jwt.secret=mySecretKey
security.jwt.expiration=86400
security.jwt.issuer=ServiceB

# Paramètres de validation
validation.enabled=true
validation.strict-mode=false

5 Créer les microservices avec .properties

Pour chaque microservice (A, B, C), créez un projet Spring Boot avec les dépendances :

  • Spring Web : Pour les endpoints REST
  • Config Client : Pour consommer la configuration
  • Actuator : Pour le monitoring

Add Dependencies to pom.xml commun pour les microservices :

       
        <!-- Client pour récupérer la configuration du Config Server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

6 Configuration des microservices

Le fichier application.properties. Il contient les informations pour se connecter au Config Server.

Fichier application.properties pour Service A :

# Nom de l'application - doit correspondre au nom du fichier de config
# Nom de l'application
spring.application.name=service-a

# Config Server location
spring.config.import=configserver:http://localhost:8888

#############################################
# ⚙️ CONFIG FETCH BEHAVIOR (Config Client Settings)
#############################################

# If the Config Server is unavailable when the client starts,
# the application will immediately fail to start ("fail fast").
# This ensures that your service never runs with outdated or missing configurations.
spring.cloud.config.fail-fast=true

# The initial waiting time (in milliseconds) before the client retries to connect
# to the Config Server after a failed attempt. Here: 1000 ms = 1 second.
# Useful when the Config Server takes time to start up or is temporarily unreachable.
spring.cloud.config.retry.initial-interval=1000

# This defines how much the waiting interval should increase between each retry attempt.
# For example, if the multiplier = 1.1, each new interval is 10% longer than the previous one.
# This helps avoid constant, aggressive retry attempts that could overload the network.
spring.cloud.config.retry.multiplier=1.1

# The maximum interval (in milliseconds) the client will wait between retries.
# Even if the multiplier increases the delay, it will never exceed this maximum.
# Here: 2000 ms = 2 seconds.
spring.cloud.config.retry.max-interval=2000

# The maximum number of retry attempts the client will make to connect to the Config Server
# before giving up and throwing an exception.
# Here: 6 attempts means the client will try 6 times in total before failing.
spring.cloud.config.retry.max-attempts=6


#############################################
# ⚙️ ACTUATOR ENDPOINTS EXPOSURE (Monitoring & Refresh)
#############################################

# By default, only a few actuator endpoints (like /actuator/health and /actuator/info)
# are exposed. This property allows you to expose all endpoints via HTTP.
# Setting it to "*" makes all actuator endpoints accessible (for example: /actuator/refresh,
# /actuator/env, /actuator/configprops, etc.).
# 🚨 For production environments, it’s recommended to limit exposure
# or secure actuator endpoints with authentication or network restrictions.
management.endpoints.web.exposure.include=*

Différence entre bootstrap.properties et application.properties

  • bootstrap.properties : Chargé en premier, pour la configuration du Config Client
  • application.properties : Chargé après, pour la configuration de l'application elle-même

Fichiers similaires pour Service B et Service C avec :

  • Service B : spring.application.name=service-b
  • Service C : spring.application.name=service-c

7 Classes principales des microservices

Service A (ServiceAApplication.java) :

package com.example.servicea;

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

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Application Spring Boot pour le Service A
 * 
 * @SpringBootApplication : Active Spring Boot
 * @RestController : Combine @Controller et @ResponseBody
 */
@SpringBootApplication
@RestController
public class ServiceAApplication {
    
    // Injection des valeurs de configuration
    @Value("${app.service.name}")
    private String serviceName;
    
    @Value("${app.service.description}")
    private String serviceDescription;
    
    @Value("${database.url}")
    private String databaseUrl;
    
    @Value("${external.api.url}")
    private String apiUrl;
    
    // Conversion d'une liste séparée par des virgules en List<String>
    @Value("#{'${app.features}'.split(',')}")
    private List<String> features;

    public static void main(String[] args) {
        SpringApplication.run(ServiceAApplication.class, args);
    }
    
    /**
     * Endpoint pour obtenir les informations du service
     * Accessible via GET /info
     */
    @GetMapping("/info")
    public Map<String, Object> getServiceInfo() {
        return Map.of(
            "name", serviceName,
            "description", serviceDescription,
            "databaseUrl", databaseUrl,
            "apiUrl", apiUrl,
            "features", features,
            "featureCount", features.size()
        );
    }
    
    /**
     * Endpoint de santé simple
     * Accessible via GET /health
     */
    @GetMapping("/health")
    public String health() {
        return serviceName + " is running!";
    }
    
    /**
     * Endpoint pour tester la configuration du cache
     */
    @GetMapping("/config")
    public Map<String, Object> getConfig() {
        return Map.of(
            "cacheEnabled", "${cache.enabled}".equals("true"),
            "cacheTtl", "${cache.ttl}",
            "apiTimeout", "${external.api.timeout}",
            "apiRetries", "${external.api.retries}"
        );
    }
}

Comprendre l'injection de configuration

  • @Value("${property.name}") : Injecte une valeur de configuration
  • #{'${list.property}'.split(',')} : Convertit une chaîne en liste
  • Les propriétés sont chargées depuis le Config Server

8 Tester la configuration locale

Suivez ces étapes pour tester votre configuration :

Ordre de démarrage important :

  1. Config Server : Doit démarrer en premier
  2. Microservices : Peuvent démarrer ensuite

Étape 1 : Démarrer le Config Server

# Dans le répertoire du Config Server
mvn spring-boot:run

Étape 2 : Vérifier l'accès aux configurations

# Tester la configuration de Service A
curl http://localhost:8888/service-a/default

Exemple de réponse du Config Server :

{
  "name": "service-a",
  "profiles": ["default"],
  "label": null,
  "version": null,
  "state": null,
  "propertySources": [
    {
      "name": "classpath:/config-repo/service-a.properties",
      "source": {
        "server.port": "8081",
        "app.service.name": "Service A",
        "app.service.description": "Premier microservice de l'application",
        "app.features": "feature1,feature2,feature3",
        "database.url": "jdbc:h2:mem:servicea",
        "database.username": "sa",
        "database.password": "password",
        "external.api.url": "https://api.servicea.com",
        "external.api.timeout": "5000"
      }
    },
    {
      "name": "classpath:/config-repo/application.properties",
      "source": {
        "app.name": "Microservices Application",
        "app.version": "1.0.0",
        "app.environment": "development",
        "logging.level.root": "INFO",
        "logging.level.com.example": "DEBUG"
      }
    }
  ]
}

Étape 3 : Démarrer les microservices

# Dans chaque répertoire de microservice
mvn spring-boot:run

Étape 4 : Tester les endpoints des microservices

# Tester Service A
curl http://localhost:8081/info
curl http://localhost:8081/health
curl http://localhost:8081/config

# Tester Service B
curl http://localhost:8082/health

# Tester Service C
curl http://localhost:8083/health

Cas d'Utilisation 2 : Configuration Git avec .properties

1 Créer un dépôt Git pour les configurations

Git est un système de contrôle de version qui permet de suivre les changements dans les fichiers de configuration.

# Créer un nouveau répertoire pour le dépôt
mkdir config-repo
cd config-repo

# Initialiser le dépôt Git
git init

# Créer les fichiers de configuration .properties
touch application.properties
touch service-a.properties
touch service-b.properties
touch service-c.properties

# Ajouter les fichiers au dépôt
git add .

# Faire le premier commit
git commit -m "Initial commit with configuration files"

# (Optionnel) Créer un dépôt distant sur GitHub/GitLab
# git remote add origin https://github.com/votre-username/config-repo.git
# git push -u origin main

Structure du dépôt Git

Votre dépôt Git devrait ressembler à cela :

config-repo/
├── application.properties      # Configuration commune
├── service-a.properties        # Configuration Service A
├── service-b.properties        # Configuration Service B
└── service-c.properties        # Configuration Service C

2 Modifier la configuration du Config Server pour Git

Mettre à jour application.properties du Config Server :

# Port du serveur Config Server
server.port=8888
#########################################################
# 🏷️ NOM DE L'APPLICATION (Application Identity)
#########################################################

# This property defines the name of the Spring Boot application.
# It identifies the Config Server itself when registered in logs, discovery services (like Eureka),
# or when monitoring via Actuator.
spring.application.name=config-server


#########################################################
# 🗂️ CONFIGURATION DU REPOSITORY GIT (Source de configuration)
#########################################################

# The Git repository where all configuration files are stored.
# Using "file://${user.home}/config-repo" means the repo is located locally
# in your user directory (e.g., C:\Users\\config-repo on Windows).
spring.cloud.config.server.git.uri=file://${user.home}/config-repo

# If you want to use a remote Git repository (for example on GitHub or GitLab),
# replace the local path above with your remote URL, like:
# spring.cloud.config.server.git.uri=https://github.com/username/config-repo.git
# You can also add authentication:
# spring.cloud.config.server.git.username=your-username
# spring.cloud.config.server.git.password=your-token


#########################################################
# 🌿 BRANCHE PAR DÉFAUT DU DÉPÔT (Git Branch)
#########################################################

# This sets which branch the Config Server will read configuration files from by default.
# Typically, repositories use "main" or "master" as the main branch.

spring.cloud.config.server.git.default-label=main


#########################################################
# 🌀 SYNCHRONISATION DU DÉPÔT GIT (Cloning and Updates)
#########################################################

# Clones the Git repository when the Config Server starts.
# Ensures that all configuration files are immediately available at startup.

spring.cloud.config.server.git.clone-on-start=true

# Forces the Config Server to perform a "git pull" on each configuration request.
# This ensures that clients always receive the latest configuration changes.
# ⚠️ Recommended only for development environments because it can slow down responses.

spring.cloud.config.server.git.force-pull=true


#########################################################
# ⏱️ PARAMÈTRES DE PERFORMANCE ET DE TEMPS (Timeouts & Refresh)
#########################################################

# Defines the maximum time (in seconds) the Config Server will wait for
# a Git operation (like clone, pull, or fetch) before timing out.
# Prevents long hangs if the Git repository is unavailable.

spring.cloud.config.server.git.timeout=5

# Defines how often (in seconds) the Config Server checks the Git repository
# for new changes when `force-pull` is enabled.
# If set to 10, the server will recheck for updates every 10 seconds.
spring.cloud.config.server.git.refresh-rate=10


#########################################################
# 🔍 ACTUATOR ENDPOINTS (Monitoring & Management)
#########################################################

# Exposes all Spring Boot Actuator endpoints over HTTP (e.g., /actuator/health,
# /actuator/info, /actuator/env, /actuator/configprops).
# Useful for debugging and monitoring, but in production you should secure them
# or limit exposure to specific endpoints for security reasons.

management.endpoints.web.exposure.include=*


#########################################################
# 🪵 NIVEAU DE LOGGING (Diagnostic et Débogage)
#########################################################

# Sets the logging level for all Spring Cloud Config components.
# "DEBUG" enables detailed logs for Git operations, refresh actions,
# and config serving — very useful for troubleshooting configuration issues.
# For production, consider using "INFO" or "WARN" to reduce log noise.

logging.level.org.springframework.cloud=DEBUG

Explication des propriétés Git :

  • spring.cloud.config.server.git.uri : URL du dépôt Git
  • spring.cloud.config.server.git.default-label : Branche principale
  • spring.cloud.config.server.git.clone-on-start : Clone au démarrage
  • spring.cloud.config.server.git.force-pull : Force la mise à jour

3 Configuration avancée Git avec authentification

Pour des dépôts privés, ajoutez l'authentification :

#########################################################
# ⚙️ CONFIGURATION GIT AVANCÉE — SPRING CLOUD CONFIG SERVER
#########################################################

# 🗂️ URI du dépôt Git contenant vos fichiers de configuration.
# Ici, il s’agit d’un dépôt privé sur GitHub (HTTPS).
# Vous pouvez stocker vos fichiers de configuration sous forme de .yml ou .properties
# (ex: service-a.yml, service-b.properties).
spring.cloud.config.server.git.uri=https://github.com/username/private-config-repo.git


#########################################################
# 🔐 AUTHENTIFICATION AU DÉPÔT GIT (Identifiants ou Token)
#########################################################

# Si le dépôt Git est privé, vous devez fournir des identifiants d’accès.
# Ces deux propriétés indiquent le nom d’utilisateur et le mot de passe/token.
spring.cloud.config.server.git.username=votre-username
spring.cloud.config.server.git.password=votre-mot-de-passe

# 💡 Bonne pratique : au lieu de mettre votre mot de passe GitHub (déconseillé),
# utilisez un **Personal Access Token (PAT)** généré depuis votre compte GitHub.
# Vous pouvez alors le configurer comme ci-dessous :
spring.cloud.config.server.git.username=token
spring.cloud.config.server.git.password=ghp_votre_token_github

# ⚠️ Ne partagez jamais votre token dans le code ou les dépôts publics.
# Utilisez un fichier `.env`, des variables d’environnement,
# ou un service de gestion des secrets (Vault, AWS Secrets Manager, etc.).


#########################################################
# 📁 RÉPERTOIRE TEMPORAIRE POUR LES CLONES DU DÉPÔT
#########################################################

# Spécifie l’emplacement local où le Config Server va cloner le dépôt Git.
# {random.value} permet de générer un nom unique à chaque lancement pour éviter les conflits.
# Exemple : /tmp/config-repo-8734fdc12
spring.cloud.config.server.git.basedir=/tmp/config-repo-{random.value}


#########################################################
# 🔍 CHEMINS DE RECHERCHE DANS LE DÉPÔT (Search Paths)
#########################################################

# Définit le sous-dossier à explorer dans le dépôt Git pour trouver les fichiers de config.
# {application} est une variable dynamique remplacée par le nom de l’application cliente
# (c’est-à-dire la valeur de spring.application.name côté client).
# Exemple : pour "service-a", le Config Server cherchera dans /service-a/
spring.cloud.config.server.git.search-paths={application}


#########################################################
# 🧩 CONFIGURATION DE MULTIPLES DÉPÔTS GIT
#########################################################

# Vous pouvez configurer plusieurs dépôts Git selon vos équipes, environnements,
# ou types de services. Chaque dépôt peut avoir son propre URI, pattern, et credentials.

# --- DÉPÔT TEAM A ---
# Tous les services dont le nom correspond au pattern "team-a-*"
# (par ex. team-a-user, team-a-order) utiliseront ce dépôt.
spring.cloud.config.server.git.repos.team-a.pattern=team-a-*
spring.cloud.config.server.git.repos.team-a.uri=https://github.com/team-a/config-repo.git

# --- DÉPÔT TEAM B ---
# Les services correspondant au pattern "team-b-*"
# seront configurés depuis ce dépôt Git distinct.
spring.cloud.config.server.git.repos.team-b.pattern=team-b-*
spring.cloud.config.server.git.repos.team-b.uri=https://github.com/team-b/config-repo.git

# Si ce dépôt est privé, vous pouvez fournir un compte spécifique
# (différent de celui utilisé pour le dépôt principal).
spring.cloud.config.server.git.repos.team-b.username=team-b-user
spring.cloud.config.server.git.repos.team-b.password=team-b-password

4 Structure avancée du dépôt Git

graph TD A[config-repo] --> B[application.properties] A --> C[service-a.properties] A --> D[service-b.properties] A --> E[service-c.properties] A --> F[shared/] F --> G[database.properties] F --> H[security.properties] A --> I[profiles/] I --> J[service-a-dev.properties] I --> K[service-a-prod.properties] I --> L[service-b-dev.properties] I --> M[service-b-prod.properties] style A fill:#4CAF50 style F fill:#2196F3 style I fill:#FF9800

Exemple de fichier shared/database.properties :

#########################################################
# 🗄️ CONFIGURATION DE BASE DE DONNÉES PARTAGÉE (DATABASE SETTINGS)
#########################################################

# 🧩 Nombre maximum de connexions dans le pool HikariCP.
# HikariCP est le pool de connexions par défaut dans Spring Boot.
# Cette valeur définit le nombre maximal de connexions simultanées
# que le pool peut maintenir vers la base de données.
# ➜ Trop faible = risque de saturation si plusieurs threads accèdent à la DB.
# ➜ Trop élevé = risque de surcharge mémoire.
# Valeur par défaut : 10 — ici augmentée à 20 pour des applications à charge moyenne.
database.hikari.maximum-pool-size=20

# 🔁 Nombre minimum de connexions maintenues en veille dans le pool.
# Même si aucune requête n’est exécutée, HikariCP gardera ce nombre de connexions ouvertes.
# Cela permet d’éviter le délai de création de connexions lors des pics de charge.
# Ici : 5 connexions toujours disponibles en standby.
database.hikari.minimum-idle=5

# ⏱️ Temps maximum (en millisecondes) que HikariCP attendra
# avant de lever une exception si aucune connexion libre n’est disponible.
# Ici : 30000 ms = 30 secondes.
# Si la base de données est lente ou surchargée, cette valeur permet d’éviter
# des blocages infinis lors de la récupération d’une connexion.
database.hikari.connection-timeout=30000


#########################################################
# ⚙️ CONFIGURATION JPA / HIBERNATE (ORM BEHAVIOR)
#########################################################

# Définit la stratégie de gestion du schéma de la base de données par Hibernate.
# Valeurs possibles :
# - none    → Hibernate ne modifie pas la base.
# - validate → Vérifie la conformité du schéma sans le modifier.
# - update   → Met à jour le schéma pour correspondre aux entités.
# - create   → Supprime et recrée le schéma à chaque démarrage.
# - create-drop → Comme create, mais supprime à l’arrêt.
# Ici : "update" pour garder la base synchronisée avec les entités
# sans perte de données (recommandé pour le développement).
database.jpa.hibernate.ddl-auto=update

# Active ou désactive l’affichage des requêtes SQL générées par Hibernate dans la console.
# true  → affiche chaque requête SQL exécutée (utile en développement ou debug)
# false → cache les requêtes pour un journal plus propre (recommandé en production)
database.jpa.show-sql=false


#########################################################
# 🧪 VALIDATION DES CONNEXIONS (Health Check SQL)
#########################################################

# Requête SQL utilisée par HikariCP pour tester si une connexion est valide.
# "SELECT 1" est une commande légère et universelle supportée par la plupart des SGBD
# (MySQL, PostgreSQL, Oracle, SQL Server, etc.).
# Cette requête est exécutée périodiquement pour garantir que les connexions
# du pool sont encore actives et éviter les erreurs du type "Connection is closed".
database.validation.query=SELECT 1

Exemple de fichier shared/security.properties :

# Configuration de sécurité partagée
security.cors.allowed-origins=*
security.cors.allowed-methods=GET,POST,PUT,DELETE
security.cors.allowed-headers=*
security.headers.xss-protection=1; mode=block
security.headers.frame-options=DENY
security.headers.content-type-options=nosniff

5 Configuration avec profils .properties

Vous pouvez créer des fichiers de configuration spécifiques aux profils :

Comprendre les profils Spring :

Les profils permettent d'avoir différentes configurations selon l'environnement :

  • default : Profil par défaut
  • dev : Développement
  • test : Test
  • prod : Production

Fichiers de configuration par profil :

  • service-a.properties - Configuration par défaut
  • service-a-dev.properties - Configuration développement
  • service-a-prod.properties - Configuration production

Exemple service-a-dev.properties :

# Configuration Service A pour l'environnement de développement
server.port=8081

# Informations du service en développement
app.service.name=Service A - Development
app.service.description=Premier microservice (Développement)
app.service.debug=true

# Base de données en mémoire pour développement
database.url=jdbc:h2:mem:devdb
database.username=sa
database.password=password
database.h2.console.enabled=true

# Logging détaillé pour développement
logging.level.root=DEBUG
logging.level.com.example=TRACE
logging.pattern.console=%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n

# API externe en mode mock
external.api.url=http://localhost:3000/mock-api
external.api.timeout=10000
external.api.mock=true

Exemple service-a-prod.properties :

# Configuration Service A pour l'environnement de production
server.port=8081

# Informations du service en production
app.service.name=Service A - Production
app.service.description=Premier microservice (Production)
app.service.debug=false

# Base de données de production
database.url=jdbc:postgresql://prod-db:5432/servicea
database.username=${DB_USERNAME}
database.password=${DB_PASSWORD}
database.pool.size=20

# Logging minimal pour production
logging.level.root=WARN
logging.level.com.example=INFO
logging.file.name=/var/log/service-a/application.log
logging.logback.rollingpolicy.max-file-size=10MB
logging.logback.rollingpolicy.total-size-cap=1GB

# Endpoints Actuator restreints en production
management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=when_authorized

# Configuration de sécurité
server.error.include-message=never
server.error.include-binding-errors=never
server.servlet.session.timeout=30m

Variables d'environnement

${DB_USERNAME} et ${DB_PASSWORD} sont des variables d'environnement :

# Sous Linux/Mac
export DB_USERNAME=prod_user
export DB_PASSWORD=secure_password

# Sous Windows
set DB_USERNAME=prod_user
set DB_PASSWORD=secure_password

Meilleures Pratiques et Améliorations

1 Structure de configuration optimale

graph TD A[Configuration Repository] --> B[Common Config] A --> C[Service Specific] A --> D[Environment Specific] A --> E[Security Config] A --> F[Feature Toggles] B --> G[application.properties] C --> H[service-a.properties] C --> I[service-b.properties] C --> J[service-c.properties] D --> K[service-a-dev.properties] D --> L[service-a-prod.properties] D --> M[service-b-test.properties] E --> N[secrets.properties] F --> O[features.properties] style A fill:#4CAF50 style B fill:#2196F3 style C fill:#2196F3 style D fill:#2196F3 style E fill:#FF5722 style F fill:#9C27B0

Exemple de features.properties :

# Feature toggles pour activer/désactiver des fonctionnalités
feature.user-management.enabled=true
feature.analytics.enabled=true
feature.reporting.enabled=false
feature.new-ui.enabled=false

# Configuration des features
feature.user-management.role-based=true
feature.analytics.real-time=false
feature.reporting.export-formats=pdf,csv