<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ronyeri Marinho on Medium]]></title>
        <description><![CDATA[Stories by Ronyeri Marinho on Medium]]></description>
        <link>https://medium.com/@ronyerimarinho?source=rss-a6315be12acd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xam-9JY8NTLtX_dUcCgZMg.jpeg</url>
            <title>Stories by Ronyeri Marinho on Medium</title>
            <link>https://medium.com/@ronyerimarinho?source=rss-a6315be12acd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:23:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ronyerimarinho/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Docker and Kubernetes?]]></title>
            <link>https://medium.com/@ronyerimarinho/why-docker-and-kubernetes-76554a64fc4a?source=rss-a6315be12acd------2</link>
            <guid isPermaLink="false">https://medium.com/p/76554a64fc4a</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Ronyeri Marinho]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 00:16:10 GMT</pubDate>
            <atom:updated>2026-11-11T00:16:10.386Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding the Problems Behind Containerization and Orchestration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHko3fpDWY_BEK-90zcKhA.png" /></figure><p>Building an application is only part of the software development journey. Once an application is ready, new challenges emerge: deploying it across different environments, managing dependencies, ensuring consistent execution, and keeping it available as the system grows.</p><p>These challenges become even more complex when applications need to run across multiple machines, handle increasing workloads, and recover from unexpected failures.</p><p>Over the years, technologies such as virtual machines and containers have changed how we build, deploy, and operate software. Docker and Kubernetes are important parts of this evolution, addressing different aspects of these challenges. <strong>But what problems led to their creation? Why do we need both technologies, and how do they work together?</strong></p><p>In this article, we’ll explore these questions by following the evolution of a simple Spring Boot application, from traditional deployment to containerization and orchestration.</p><p>Our goal is not simply to learn commands or memorize components, but to understand <strong>why these technologies exist and what problems they solve</strong>.</p><h3>1. Before Containers: Understanding the Deployment Problem</h3><p>Imagine you’ve just finished developing an order management API using Java and Spring Boot. Everything works perfectly on your machine, your tests pass, and you’re ready to deploy it.</p><p><strong>But how do you ensure the application will run correctly on another machine?</strong> To understand this challenge, let’s look at how applications were traditionally deployed.</p><h4><strong>1.1. Running Applications on Physical Servers</strong></h4><p>Traditionally, deploying an application meant preparing a physical server with everything required to execute it:</p><ul><li>An operating system, such as Linux.</li><li>A compatible Java Runtime Environment (JRE) or JDK.</li><li>Required system libraries and dependencies.</li><li>Environment variables and network configurations.</li><li>Access to external services, such as databases.</li></ul><p>Once everything was configured, the application could be started:</p><pre>java -jar order-api.jar</pre><p>The OS starts a Java process, which initializes the Java Virtual Machine (JVM). The JVM then loads and executes the application’s bytecode, interacting with the underlying OS and hardware. A simplified execution stack could be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbFW6bVMaEZdBHE2lPh25A.png" /><figcaption>Figure 01 — Application → JVM → Operating System → Hardware</figcaption></figure><p>This approach works perfectly well, <strong>but problems emerge as the number of applications and environments increases</strong>.</p><h4><strong>1.2. The Environment Consistency Problem</strong></h4><p>Imagine our company now has three applications:</p><ul><li>Order API with Java 21</li><li>Payment API with Java 17</li><li>Notification API with Java 11</li></ul><p>Each application has its own runtime requirements, dependencies and configurations. Developers may also use different OS, Java versions, and local configurations. As a result, an application might work perfectly on one machine but fail on another due to differences in the execution environment.</p><p>This is the familiar <strong>“It works on my machine!”</strong> problem.</p><p>One of the possible solution is to isolate application into separate environments rather than relying on a single shared OS. <strong>This brings us to virtualization.</strong></p><h4><strong>1.3. Virtual Machines: Isolating Environments</strong></h4><p>Hardware virtualization allows a physical server to run multiple virtual machines (VMs). A component called <strong>hypervisor</strong> creates and manages these virtual machines, allocating physical resources such as CPU, memory, and storage to each one.</p><p>Each VM behaves like an independent computer, with its own operating system, processes, and applications. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iThuNJ8fWfPuZWy9o3MlJw.png" /><figcaption>Figure 02 — Physical Server → Hypervisor → Three Virtual Machines, each containing its own Guest OS and Java Application</figcaption></figure><p>This approach provides several advantages:</p><ul><li><strong>Isolation:</strong> applications run in separate operating system environments.</li><li><strong>Flexibility:</strong> different OSs can run on the same physical hardware.</li><li><strong>Consistency:</strong> VM images can help standardize environments across machines.</li></ul><p>However, each virtual machine typically requires its own guest operating system, consuming additional memory and storage and requiring independent maintenance.</p><p>Virtualization solved many infrastructure challenges, but it also introduced operational overhead.</p><h4><strong>1.4. Containers: A Different Approach to Isolation</strong></h4><p>What if we could isolate applications without running a complete operating system for each one? Containers provide a different approach.</p><p>Instead of virtualizing hardware and running multiple guest operating systems, containers allow application to execute in isolated environments while sharing the host operating system kernel. On Linux, this isolation relies on kernel features such as:</p><ul><li><strong>Namespaces: </strong>isolate the visibility of system resources, such as processes and network interfaces.</li><li><strong>Control groups (cgroups):</strong> allow resource consumption, such as CPU and memory, to be controlled and accounted for.</li></ul><p>Unlike virtual machines, containers don’t require a separate guest operating system for each application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0LOoRs9UCzGOciQ88PE7w.png" /><figcaption>Figure 03 — Virtual Machines vs. Containers: Separate Guest OSs vs. Shared Host Kernel</figcaption></figure><p>This makes containers generally more lightweight and faster to start than traditional VMs. However, sharing the host kernel also means containers don’t provide exactly the same isolation boundaries as virtual machines. Resource contention and kernel-level security remain important considerations.</p><h4><strong>1.5. From Traditional Servers to Containers</strong></h4><p>We’ve seen how application deployment evolved:</p><ul><li><strong>Bare Metal:</strong> Applications run directly on physical servers.</li><li><strong>Virtual Machines:</strong> Multiple virtual computers share physical hardware.</li><li><strong>Containers:</strong> Applications run in isolated environments sharing the host kernel.</li></ul><p>Each approach addresses different infrastructure challenges, but containers introduce an especially useful capability: <strong>applications can be packaged and distributed in a consistent way across environments</strong>.</p><p>But how do we actually package an application into a container? How do we share it with other developers or deploy it to a server? And as the number of containers grow, how do we manage them across multiple machines?</p><p>These questions lead us to Docker and, eventually, Kubernetes.</p><h3>2. Docker: Packaging Applications</h3><p>In the previous chapter, we explored the challenges of deploying applications across different environments. We saw how virtual machines helped isolate applications, but also introduced additional overhead by requiring a complete guest operating system for each instance.</p><p>Containers offer a different approach: instead of packaging an entire operating system, they package an application together with everything it needs to run. <strong>This is where Docker comes in</strong>.</p><h4>2.1. From Application to Image</h4><p>Imagine we have finished developing our Spring Boot order-api. It runs perfectly on our machine, but how can we ensure it behaves the same way on a test server or in production?</p><p>Docker addresses this problem by allowing us to define how an application should be packaged into an <strong>image</strong>.</p><p>An image is an immutable template containing the application, its runtime, required dependencies, and configuration needed to start it. For example, our image can include a Java 21 runtime and the compiled Spring Boot JAR. Once created, this image can be used to start one or more <strong>containers</strong>.</p><p>The distinction is important:</p><ul><li><strong>Image:</strong> the packaged template used to create containers.</li><li><strong>Container:</strong> a running instance of an image, with its own isolated process environment and writable layer.</li></ul><p>Think of an image as a class and a container as an object instantiated from it. The same image can create multiple independent containers, each running its own instance of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1JkCm-h6Mi4hLFTj3Odhg.png" /><figcaption>Figure 04 — From Dockerfile to Container: a Dockerfile defines how an image is built, and that image can be used to create one or more running containers.</figcaption></figure><h4>2.2. Defining the Image with a Dockerfile</h4><p>But how do we tell Docker what should go into an image? We use a file called Dockerfile, which contains the instructions for building it. For our Spring Boot application, a simple example would look like this:</p><pre>FROM eclipse-temurin:21-jre<br><br>WORKDIR /app<br><br>COPY target/order-api.jar app.jar<br><br>EXPOSE 8080<br><br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>Each instruction has a specific purpose:</p><ul><li>FROM defines the base image, in this case, one containing a Java 21 runtime.</li><li>WORKDIR sets the working directory inside the image.</li><li>COPY adds our compiled application to the image.</li><li>EXPOSE documents the port the application listens on.</li><li>ENTRYPOINT defines the command used to start the application.</li></ul><p>We can then build the image:</p><pre>docker build -t order-api:1.0 .</pre><p>And start a container from it:</p><pre>docker run -p8080:8080 order-api:1.0</pre><p>Notice that the application runs inside the container, while port 8080 is published on the host machine so external clients can reach it. The server no longer needs Java installed directly on its operating system. It needs a compatible container runtime to execute the image.</p><h4>2.3. Building Efficient Images</h4><p>Docker images are built using layers. Each filesystem-changing instruction can contribute a layer to the final image, and Docker can reuse previously built layers through its build cache.</p><p>This means that the order of instructions matters.</p><p>For example, when building a Java application, we can copy the dependency definition first and download dependencies before copying the source code. If only the source code changes, Docker may reuse the dependency-related layers instead of downloading everything again. We can also use <strong>multi-stage</strong> <strong>builds</strong> to separate compilation from execution.</p><p>A Maven image can compile our application, while a smaller Java runtime image is used for the final stage. Only the resulting JAR is copied into the final image, leaving behind build tools and unnecessary files. The result is often a smaller and more focused image.</p><h4>2.4. Sharing Images Through Registries</h4><p>So far, we have built an image locally. But how do we make it available to other environments? This is the role of a <strong>container registry</strong>.</p><p>A registry stores and distributes container images. Docker Hub, Amazon Elastic Container Registry (ECR), and Google Artifact Registry are examples. We can tag our image with a repository name and version, then push it to a registry:</p><pre>docker tag order-api:1.0 my-repository/order-api:1.0<br><br>docker push my-repository/order-api:1.0</pre><p>A production server can then retrieve the same image:</p><pre>docker pull my-repository/order-api:1.0</pre><p>This creates a consistent delivery process: build the image once, store it in a registry, and deploy that same artifact across environments.</p><p>Version tags also help control which application version is deployed. Publishing version 2.0, for example, does not automatically change containers already running version 1.0. A new deployment must explicitly use the new image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmhBRfQ5fv38KCq5sza1FQ.png" /><figcaption>Figure 05 — From development to production: a Docker image is built once, pushed to a container registry, and pulled by different environments to ensure consistent deployments.</figcaption></figure><h4>2.5. Beyond a Single Container</h4><p>Real applications rarely consist of a single process. Our order-api, for example, might depend on PostgreSQL and communicate with other services. Docker provides networking so containers can communicate, and <strong>volumes</strong> allow data to persist independently of a container’s lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJA_hhTCqA-wgWbO3LMahQ.png" /><figcaption>Figure 06 — Docker Compose defines and runs multiple services within a shared network. The order-api communicates with PostgreSQL, while a persistent volume keeps database data independent of the container lifecycle.</figcaption></figure><p><strong>Docker Compose</strong> makes this setup easier by allowing us to define multiple services, their networks, volumes, and configuration in a single YAML file. With one command, we can start the entire application environment:</p><pre>docker compose up -d</pre><p>This is particularly useful during development and for managing applications on a single host. However, as our system grows, we may need to run containers across multiple machines, distribute traffic, recover from failures, and continuously maintain the desired number of application instances.</p><p>Docker gives us the building blocks to package and run applications. But managing them across a distributed environment introduces another challenge.</p><p>And that is the problem <strong>Kubernetes</strong> was designed to address.</p><h3>3. Kubernetes: Orchestrating Containers</h3><p>Why Container Orchestration?</p><p>Docker solves an important problem: it packages an application and its dependencies into a consistent, portable image. However, running a few containers on a single machine is very different from operating dozens or hundreds of containers across multiple machines.</p><p>Consider our order-api. As the application grows, we may need multiple instances to handle incoming requests. Those instances might run on different machines, and some of them may become unavailable. We also need to deploy new versions without unnecessarily interrupting the service.</p><p>Docker Compose helps define and run multi-container applications, but coordinating workloads across a cluster of machines introduces a different level of complexity. This is where <strong>container orchestration</strong> becomes important.</p><p>Container orchestration automates tasks such as deploying containers, maintaining the desired number of replicas, distributing workloads across machines, handling failures, and managing application updates. One of the most widely adopted platforms for this purpose is <strong>Kubernetes</strong>.</p><h4>3.1. Understanding a Kubernetes Cluster</h4><p>A Kubernetes cluster is a group of machines working together to run containerized applications. These machines are called <strong>Nodes</strong>, and they have two main roles: Control Plane and Worker Nodes.</p><p>The <strong>Control Plane</strong> is responsible for managing the cluster. It exposes the Kubernetes API, stores the cluster state, schedules workloads, and coordinates the controllers that continuously reconcile the actual state with the desired state. Some of its main components are:</p><ul><li><strong>API Server:</strong> the entry point for Kubernetes operations. Tools such as kubectl communicate with the cluster through this API.</li><li><strong>etcd:</strong> a distributed key-value store that keeps the cluster’s state and configuration.</li><li><strong>Scheduler:</strong> selects an appropriate Worker Node for Pods that have not yet been assigned to a machine.</li><li><strong>Controllers:</strong> continuously observe the cluster and take action when its actual state differs from the desired state.</li></ul><p><strong>Worker Nodes</strong> are responsible for running application workloads. They contain components such as:</p><ul><li><strong>Kubelet:</strong> an agent that communicates with the Control Plane and ensures that the Pods assigned to its Node are running as expected.</li><li><strong>Container Runtime:</strong> the software responsible for executing containers, such as containerd or CRI-O.</li></ul><p>This separation allows Kubernetes to coordinate workloads across multiple machines while keeping application execution distributed throughout the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KH74DZzwyDhbUJ8EDkydcQ.png" /><figcaption>Figure 07 — An overview of a Kubernetes cluster: the Control Plane manages the cluster state and coordinates workloads, while Worker Nodes run application Pods through their container runtimes.</figcaption></figure><h4>3.2. Pods, Deployment and ReplicaSets</h4><p>In Kubernetes, the smallest deployable unit is not a container, but a Pod.</p><p>A Pod groups one or more containers that share network resources and can share storage volumes. Although multiple containers can run inside the same Pod, the most common pattern is to have one main application container per Pod.</p><p>For our order-api, we could start with a single Pod. But what happens when traffic increases, or when that Pod becomes unavailable? Kubernetes provides abstractions to manage this automatically.</p><p>A <strong>ReplicaSet </strong>ensures that a specified number of matching Pod replicas are running. If one disappears, the ReplicaSet controller detects the difference and creates another Pod to restore the desired count.</p><p>A <strong>Deployment</strong> manages ReplicaSets and provides declarative updates to an application. Instead of manually creating and replacing Pods, we describe the desired configuration:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: order-api<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: order-api<br>  template:<br>    metadata:<br>      labels:<br>        app: order-api<br>    spec:<br>      containers:<br>        - name: order-api<br>          image: order-api:1.0</pre><p>With replicas: 3, we are telling Kubernetes that we want three instances of the application running. Kubernetes continuously works toward that desired state. If a Pod is deleted or becomes unavailable, the controllers attempt to restore the expected number of replicas, provided the cluster has the resources and conditions to required to do so.</p><p>This principle is known as <strong>declarative management</strong>: we describe what the system should look like, and Kubernetes works to keep it that way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eehxy608hpWw1z4eCdXByA.png" /><figcaption>Figure 08 — A Deployment manages the application lifecycle and its ReplicaSets. Each ReplicaSet maintains the desired number of Pod replicas, creating replacements when existing Pods become unavailable.</figcaption></figure><h4>3.3. Services and Networking</h4><p>There is another challenge with running multiple Pods: their IP addresses are not permanent.</p><p>Pods can be created, deleted, and replaced at any time. If another application depends directly on a Pod’s IP address, communication can break whenever that Pod is replaced. Kubernetes solves this problem with <strong>Services</strong>.</p><p>A Service provides a stable network endpoint for a group of Pods. It uses labels to identify the Pods that belong to it and makes them accessible through a consistent name and address. For example, another service could communicate with our application using:</p><pre>http://order-api:80</pre><p>Instead of knowing the IP address of each Pod, the calling application only needs to know the Service name. Kubernetes DNS, commonly provided by CoreDNS, resolves that name within the cluster.</p><p>Services can also expose applications outside the cluster. A LoadBalancer Service can provision an external load balancer when supported by the underlying infrastructure. For HTTP and HTTPS traffic, an Ingress Controller or Gateway can provide an additional routing layer, directing requests to different Services.</p><p>This allows applications to communicate without depending on the lifecycle or location of individual Pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ey7L0wmf8IC9f6xmNKdf-w.png" /><figcaption>Figure 09 — Kubernetes Services provide stable network endpoints for application Pods. External traffic can enter through a LoadBalancer Service, while internal applications communicate using Service names resolved by Kubernetes DNS.</figcaption></figure><h4>3.4. Health Checks and Application Configuration</h4><p>Keeping the desired number of Pods running is only part of the problem. Kubernetes also needs to understand whether an application has started correctly and whether it is ready to receive traffic. For this, Kubernetes provides three types of health probes:</p><ul><li><strong>Startup Probe:</strong> determines whether the application has completed its startup process.</li><li><strong>Liveness Probe:</strong> checks whether the application is still functioning. Repeated failures can cause the container to be restarted.</li><li><strong>Readiness Probe:</strong> determines whether the application is ready to receive traffic. If it fails, the Pod is removed from the eligible endpoints of its Service, without necessarily restarting the container.</li></ul><p>These probes are particularly useful for applications such as our Spring Boot order-api, where startup time and dependency availability can affect readiness.</p><p>Kubernetes also provides mechanisms for separating configuration from application images. <strong>ConfigMaps</strong> store non-sensitive configuration, while <strong>Secrets</strong> are intended for sensitive values such as credentials and tokens. Secrets require appropriate access controls and encryption practices; their values are not automatically protected just because they are stored as Secrets.</p><p>Together, these capabilities help applications run consistently across different environments without embedding environment-specific configuration into their container images.</p><h4>3.5. From Containers to Orchestration</h4><p>Docker and Kubernetes address different parts of the same problem.</p><p>Docker provides a way to package applications and their dependencies into portable images. Kubernetes takes those containers and coordinates their execution across a cluster, helping maintain the desired state of the system.</p><p>However, orchestration does not automatically guarantee high availability or eliminate operational complexity. Capacity, replica distribution, health checks, networking, and application design still matter.</p><p>Understanding these responsibilities is essential to building systems that can evolve beyond a single machine.</p><p>And that bring us to the final question: how do containerization and orchestration fit together in modern software delivery?</p><h3>Conclusion: From Packaging to Orchestration</h3><p>Modern applications need more than code that works on a developer’s machine. They need to run consistently across environments, scale as demand changes, recover from failures, and evolve without unnecessary disruption.</p><p>Docker addresses the packaging problem. By combining an application and its dependencies into a portable image, it makes deployments more predictable and simplifies the way applications are distributed and executed.</p><p>Kubernetes builds on that foundation by coordinating containers across a cluster of machines. It helps maintain the desired number of application instances, manage deployments, provide stable networking, and respond to failures.</p><p>Together, these technologies represent two important layers of modern application infrastructure:</p><ul><li><strong>Docker:</strong> packages the application and its runtime dependencies.</li><li><strong>Kubernetes:</strong> orchestrates how those application run across a cluster.</li></ul><p>Understanding why these technologies exist is just as important as knowing how to use them. Once we understand the problems they solve, their abstractions and responsibilites become much easier to reason about.</p><p>Ultimately, the goal is not simply to run containers. It is to build systems that can be deployed, operated, and evolved reliably.</p><p>I sincerely hope this article has helped you better understand the problems behind containerization and orchestration, and how Docker and Kubernetes help address them in modern software development.</p><p>If you have any questions, suggestions, or simply want to exchange ideas about these technologies, feel free to connect with me on <a href="https://www.linkedin.com/in/ronyeri-marinho/"><strong>LinkedIn</strong></a>.</p><p>Thank you for following along until the end, and see you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76554a64fc4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keycloak + Spring: A Practical Guide to Securing Your APIs]]></title>
            <link>https://medium.com/@ronyerimarinho/keycloak-spring-um-guia-pr%C3%A1tico-para-proteger-suas-apis-f8bb3c991bb1?source=rss-a6315be12acd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8bb3c991bb1</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Ronyeri Marinho]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 17:41:43 GMT</pubDate>
            <atom:updated>2026-11-07T10:00:31.925Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern applications, sooner or later you will face authentication and authorization: login, access control, tokens, roles, refresh tokens, password security… the list is long. Implementing all of this from scratch in every project is not only time-consuming, but also significantly increases the risk of security flaws and inconsistencies between systems. And this is exactly where <a href="https://www.keycloak.org/"><strong>Keycloak</strong></a><strong> </strong>comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUBkgMfqieSEn9cbr0McHA.png" /></figure><p>Keycloak is an <strong>Identity and Access Management (IAM)</strong> server that centralizes the entire authentication and authorization layer of your application, solving many common problems such as:</p><ul><li>User management</li><li>Login and logout</li><li>Permissions and roles management</li><li>Token issuance and validation (OAuth 2.0 / OpenID Connect)</li><li>Integration with multiple applications using the same identity base</li><li>Easy integration with social login providers (Google, GitHub, etc.)</li></ul><p><strong>But why integrate it with Spring?</strong> The answer lies in the combination of productivity and security. By integrating Keycloak with your API, you drastically reduce the amount of manual configuration required for these flows and <strong>delegate the responsibility to a specialized tool</strong>, consuming only already validated JWT tokens in your application.</p><p>In addition, centralizing the identity provider fits perfectly into microservices architectures, allowing multiple applications to share the same authentication system and enabling a true single sign-on experience for users.</p><p>If you have ever struggled to build all this “by hand”, this guide will save you a significant amount of time.</p><h3>1. A brief tour of Keycloak’s main features</h3><p>The goal here is to stay as hands-on as possible, but some concepts need to be introduced first so that the configuration makes sense and does not turn into a purely mechanical sequence of steps without context.</p><p>Keycloak is an open-source <strong>Identity and Access Management (IAM)</strong> platform that centralizes authentication (proving who the user is) and authorization (defining what they are allowed to do). Instead of each application implementing these responsibilities individually, they delegate this work to an identity server.</p><p>Compatible with widely adopted standards such as <a href="https://oauth.net/2/"><strong>OAuth 2.0</strong></a>, <a href="https://openid.net/developers/how-connect-works/"><strong>OpenID Connect</strong></a>, and <a href="https://auth0.com/pt/intro-to-iam/what-is-saml"><strong>SAML 2.0</strong></a>, Keycloak integrates easily with web applications, mobile apps, and REST APIs, regardless of the backend technology.</p><p>In practice, it provides a built-in, ready-to-use, and fully customizable login page, along with several endpoints for authentication, token refresh, and logout. This allows applications to use either a standard login interface or purely API-based authentication flows, without being tied to a specific UI model.</p><p>In addition, Keycloak offers a complete administrative interface for managing users, roles, and permissions, as well as integration with external identity providers such as Google, GitHub, and others.</p><p>It is worth noting that Keycloak is a very robust and feature-rich tool. In this guide, we will focus on the essentials to get you started, but for a deeper understanding, the official documentation and complementary materials are excellent next steps.</p><h3>2. Running Keycloak and PostgreSQL with Docker</h3><p>In this step, we will run <strong>Keycloak</strong> inside <strong>Docker </strong>containers and use <strong>PostgreSQL</strong> as the database.</p><p>To simplify the setup, we will use a docker-compose.yml file containing only the essentials: the Keycloak service, the PostgreSQL service, and the configuration required for both to communicate properly.</p><p>Below is the content of the file:</p><pre>services:<br>  db:<br>    container_name: psql-db-demo<br>    image: postgres<br>    restart: always<br>    environment:<br>      - POSTGRES_USER=postgres<br>      - POSTGRES_PASSWORD=root<br>    volumes:<br>      - pgdata:/var/lib/postgresql/data<br>      - ./init-keycloak-database.sql:/docker-entrypoint-initdb.d/init-keycloak-db.sql<br>    ports:<br>      - 5432:5432<br>  keycloak:<br>    container_name: keycloak-demo<br>    image: quay.io/keycloak/keycloak:26.1.0<br>    environment:<br>      - KC_BOOTSTRAP_ADMIN_USERNAME=admin<br>      - KC_BOOTSTRAP_ADMIN_PASSWORD=admin<br>      - KC_DB=postgres<br>      - KC_DB_URL=jdbc:postgresql://db:5432/keycloak<br>      - KC_DB_USERNAME=postgres<br>      - KC_DB_PASSWORD=root<br>    ports:<br>      - 8181:8080<br>    command: start-dev<br>    depends_on:<br>      - db<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;pg_isready&quot;, &quot;-U&quot;, &quot;root&quot;]<br>      interval: 10s<br>      retries: 5<br>volumes:<br>  pgdata:</pre><p>This file defines:</p><ul><li>A <strong>PostgreSQL</strong> container, with user, password, exposed port, and a volume for data persistence;</li><li>A <strong>Keycloak</strong> container, with a property configured to run in development mode (start-dev);</li><li>The necessary environment variables for Keycloak to automatically connect to the database.</li></ul><p>In addition, we include a database initialization script named init-keycloak-database.sql, located at the root of the project, with the following content:</p><pre>CREATE DATABASE keycloak WITH ENCODING &#39;UTF8&#39;;</pre><p>This script ensures that the database used by Keycloak is automatically created when the PostgreSQL container starts for the first time.</p><p>Pay special attention to the following variable:</p><pre>KC_DB_URL=jdbc:postgresql://db:5432/keycloak</pre><p>Here, db is the name of the PostgreSQL service defined in docker-compose.yml, allowing the containers to find each other through Docker’s internal network without the need for manual IP configuration. With everything configured, simply run:</p><pre>docker compose up -d</pre><p>In just a few seconds, your Keycloak and PostgreSQL instances will be up and running. I used simple usernames, passwords, and ports to make the example easier to follow, but feel free to customize them according to your needs.</p><p>The Keycloak admin console will be available at:</p><pre>http://localhost:8181</pre><figure><img alt="Tela de autenticação do Keycloak com campos para usuário ou e-mail, senha e botão de login, apresentada como interface do painel administrativo." src="https://cdn-images-1.medium.com/max/1024/1*ikjnVeOFjSUQGm1dV-t49Q.png" /><figcaption>Figure 1 — Keycloak Admin Console login screen.</figcaption></figure><p>To access it, use the username and password defined in the environment variables:</p><ul><li>KC_BOOTSTRAP_ADMIN_USERNAME</li><li>KC_BOOTSTRAP_ADMIN_PASSWORD</li></ul><h3>3. What needs to be configured in Keycloak?</h3><p>After logging into the admin console, you will quickly notice the number of features and configuration options available. Let’s start with the most important concept of all: the <strong>Realm</strong>.</p><p><strong>3.1 Configuring the Realm</strong></p><p>A <strong>realm</strong> in Keycloak works as an isolated space that contains all the security configuration for one or more applications. It is inside a realm that we define users, credentials, roles, permissions, and all the other elements we will see next.</p><p>Think of a realm as the <em>security universe</em> of your project. Each realm is completely independent from the others, which makes it perfect for separating different projects or even environments such as development, staging, and production.</p><p>At this point, you have probably noticed, in the top-left corner of the screen, the existence of a realm called <strong>master</strong>. This realm is responsible for managing the Keycloak instance itself — including the user we are currently using to access the admin console — <strong>and for this reason, it is not recommended to use it for applications</strong>.</p><p>So let’s create our own.</p><p>Click on <strong>Create realm</strong>, choose a name that makes sense for your context, and complete the creation. With that, we now have our isolated security environment ready to receive the next configurations.</p><figure><img alt="A figura exibe a tela inicial do Keycloak após a realização do login. Ela contém uma mensagem de boas vindas e botões com links para a documentação do Keycloak. Ela também possui um menu lateral com os recursos disponíveis no realm atual, que é o realm master." src="https://cdn-images-1.medium.com/max/1024/1*JNQjxqoAXUKRxM7SX2zlUQ.png" /><figcaption>Figure 2 — Keycloak home screen with the master realm.</figcaption></figure><p><strong>3.2 Configuring the Client</strong></p><p>A <strong>client</strong> represents an application or service that will use Keycloak to authenticate users or validate access. In other words, <strong>the client is how your application <em>exists</em> inside Keycloak</strong>.</p><p>This is where we define:</p><ul><li>how the application communicates with Keycloak,</li><li>which authentication flows are enabled,</li><li>and which security behaviors are allowed.</li></ul><p>In the menu of your new realm, go to the <strong>Clients</strong> section and create a new one. Some default clients will already exist and can be ignored.</p><p>When creating it, fill in:</p><ul><li><strong>Client ID</strong>: the application identifier (in my case: keycloak-spring-xp)</li><li><strong>Name</strong> e <strong>Description</strong>: optional, but useful for organization.</li></ul><figure><img alt="A imagem apresenta o formulário de criação de um client dentro do Keycloak, onde existem os campos Client ID, Name e Description, além de botões de ação para cancelar ou ir para a próxima etapa da criação." src="https://cdn-images-1.medium.com/max/1024/1*k5KEPoht1amNyGFKUVk-Ug.png" /><figcaption>Figure 3 — Client general configuration form.</figcaption></figure><p><strong>3.2.1 Client Types</strong></p><p>The client type defines how the application authenticates with Keycloak:</p><ul><li><strong>Public:</strong> used by applications that cannot securely store secrets, such as SPAs (e.g., Angular, React). <strong>This type does not require a <em>client secret</em> for authentication</strong>.</li><li><strong>Confidential (private)</strong>: used by applications running on secure servers, such as backends and APIs. <strong>These applications use a <em>client secret</em> for authentication</strong>, ensuring more secure communication with the identity server.</li></ul><p>Since we are working with an API, we choose the <strong>Confidential</strong> type.</p><p><strong>3.2.2 Authentication Flows</strong></p><p>Keycloak offers several flows. The main ones are:</p><ul><li><strong>Standard Flow</strong>: the most recommended flow from a security standpoint. It is used in applications that have a frontend and support redirection. In this model, the user does not receive the access token directly, but rather an authorization code, which is later exchanged for tokens.</li><li><strong>Implicit Flow (not recommended)</strong>: similar to the Standard Flow, but returns the token directly after authentication. Because it exposes the token and introduces security risks, its use is discouraged.</li><li><strong>Direct Access Grants</strong>: recommended only for specific scenarios, like ours, where there is only an API and no frontend. This flow allows direct authentication via API using <strong>username and password</strong>.</li><li><strong>Service Accounts Roles</strong>: used for system-to-system authentication, allowing a service to authenticate with another without the involvement of an end user.</li></ul><figure><img alt="A imagem apresenta o segundo passo no fluxo de configuração de um client. Nele, há um campo para habilitar a confidencialidade do client, e também as opções de autenticação disponíveis. Além disso, há botões de ação para voltar ao passo anterior, cancelar a criação ou ir para o próximo passo." src="https://cdn-images-1.medium.com/max/1024/1*z3rlnr-BQIQ_4rDa6wzVIA.png" /><figcaption>Figure 4 — Client flow configuration form.</figcaption></figure><p>Redirect configuration (URLs) is important for applications with a frontend, as it defines where Keycloak should redirect the user after events such as login, logout, and others. In our scenario, this configuration does not directly affect our authentication flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0HyNpd_g2pcyhaM4VnB-w.png" /><figcaption>Figure 5 — Client login configuration form.</figcaption></figure><p><strong>3.3 Access Token Lifetime</strong></p><p>At this point, we have created the<strong> isolated security space</strong> (<strong>Realm</strong>) and the <strong>resource that represents our application</strong> and defines how it authenticates with Keycloak (<strong>Client</strong>). With this, we already have the essentials needed to integrate the Spring application and protect it with Keycloak.</p><p>By default, the access token lifetime is <strong>5 minutes</strong>. This value can be adjusted in the Realm settings by navigating to:</p><p><strong>Realm Settings<em> → </em>Tokens → Access Token Lifespan.</strong></p><figure><img alt="A imagem apresenta um menu de configuração do Keycloak, chamado Realm Settings. Nele, existem diversas abas com diferentes configurações. A aba Tokens está selecionada e um formulário com diversos campos está sendo exibido." src="https://cdn-images-1.medium.com/max/1024/1*OM7j0Ql5sCAUplFc_oqCog.png" /><figcaption>Figure 6 — Token-related configuration screen.</figcaption></figure><p>These are the minimum configurations required to start protecting your API. Keycloak offers many more features, and my recommendation is to explore the official documentation and <a href="https://www.keycloak.org/guides">additional guides</a> at your own pace.</p><h3>4. How does the API connect to Keycloak?</h3><p>The first step was to create the API using Spring Initializr and add the required dependencies. For our context, the most important ones are:</p><ul><li><strong>Spring Security</strong>: responsible for intercepting HTTP requests, protecting the application’s endpoints, and enforcing authentication and authorization rules.</li><li><strong>OAuth2 Resource Server</strong>: pallows the API to act as a Resource Server, trusting Keycloak as the Authorization Server and only validating the JWT tokens already issued by it, without implementing any custom authentication logic.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A66EyMubRzwZbyCBxd5k1A.png" /><figcaption>Figure 7 — Project configuration screen in Spring Initializr.</figcaption></figure><p>To keep the example focused and simple, a basic <em>Hello World</em> endpoint was created:</p><pre>// imports omitted...<br><br>@RestController<br>public class HelloWorldController {<br><br>    @GetMapping(&quot;hello-world&quot;)<br>    public String saysHelloWorld() {<br>        return &quot;Hello World!&quot;;<br>    }<br>}</pre><p>At this point, the response of this endpoint will be <strong>401 (Unauthorized)</strong> if you try to access it. This behavior is expected and is part of the <em>secure by default</em> principle (<em>deny by default</em>): once Spring Security is added, all requests are automatically protected and require a valid token.</p><p><strong>4.1 Configuring </strong><strong>application.yml</strong></p><p>For the API to accept tokens issued by Keycloak, we need to <strong>inform who the token issuer is</strong> and <strong>how to validate its signature</strong>.</p><p>The issuer-uri property represents the entity that issues the tokens — in our case, the Keycloak Realm. With this information, Spring uses the OpenID Connect Discovery mechanism to automatically discover the endpoints and keys required for validation.</p><p>The jwk-set-uri property points directly to the endpoint that exposes the public keys used to verify the signature of JWT tokens.</p><p>These configurations are done in the application.yml (or application.properties, depending on your project setup):</p><pre>spring:<br>  application:<br>    name: keycloak-spring-xp<br>  security:<br>    oauth2:<br>      resource-server:<br>        jwt:<br>          issuer-uri: ${APP_OAUTH2_JWK_ISSUER_URI:http://localhost:8181/realms/keycloak-demo}<br>          jwk-set-uri: ${spring.security.oauth2.resource-server.jwt.issuer-uri}/protocol/openid-connect/certs</pre><p>Now we need to configure application security to behave as a <strong>stateless Resource Server</strong>, requiring authentication for all requests and automatically validating JWT tokens:</p><pre>// imports omitted...<br><br>@Configuration<br>@EnableWebSecurity<br>public class SecurityConfiguration {<br><br>    @Bean<br>    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {<br>        return httpSecurity<br>                .cors(Customizer.withDefaults())<br>                .csrf(CsrfConfigurer::disable)<br>                .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -&gt;<br>                        authorizationManagerRequestMatcherRegistry<br>                                .anyRequest().authenticated()<br>                )<br>                .oauth2ResourceServer(httpSecurityOAuth2ResourceServerConfigurer -&gt;<br>                        httpSecurityOAuth2ResourceServerConfigurer.jwt(Customizer.withDefaults()))<br>                .sessionManagement(httpSecuritySessionManagementConfigurer -&gt;<br>                        httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))<br>                .build();<br>    }<br>}</pre><p>And that’s it.</p><p>At this point, Spring already trusts Keycloak as the identity provider, and every request must present a valid token to access any API endpoint. But a few questions remain:</p><blockquote>How do we authenticate?<em><br></em>With which user?<em><br></em>And what is the authentication endpoint?</blockquote><p>That is exactly what we will cover in the next chapter.</p><h3>5. Obtaining and using the access token</h3><p>Inside the Keycloak instance, go to <strong>Realm Settings</strong> and, in the <strong>General</strong> tab, scroll down to the <strong>Endpoints</strong> section. There you will find two important links — the first one is the <strong>OpenID Endpoint Configuration</strong>.</p><p>When you click this link, Keycloak will display a document containing all the URLs related to the OpenID Connect protocol. Among them is the endpoint responsible for issuing tokens. Example:</p><pre>http://localhost:8181/realms/keycloak-demo/protocol/openid-connect/token</pre><p>It is through this endpoint that we authenticate with Keycloak and obtain the <strong>access token</strong>, which will then be sent in requests to our Spring API.</p><p>In our scenario, we use this endpoint to authenticate via <strong>Direct Access Grants</strong>. The complete structure of the request in <a href="https://www.postman.com/">Postman</a> can be seen below:</p><figure><img alt="A imagem exibe uma captura de tela do aplicativo Postman. Nele, estamos configurando uma requisição HTTP de tipo POST, sua URL e seus parâmetros para autenticação junto ao Keycloak." src="https://cdn-images-1.medium.com/max/1024/1*MzWfOq-KtpujPbTFCNUxwQ.png" /><figcaption>Figure 8 — HTTP request for authentication in Keycloak using Postman.</figcaption></figure><p><strong>5.1 Authentication request parameters</strong></p><p>To authenticate against Keycloak’s token endpoint, we need to send a few parameters in the request body. Each one plays a specific role in the process:</p><ul><li><strong>Grant Type: </strong>defines which authentication flow is being used. In our case, we use password, which indicates the Direct Access Grants flow, where the user authenticates directly with username and password. This parameter is essential for Keycloak to understand how to process the request.</li><li><strong>Client ID: </strong>identifies which Client is requesting the token. It represents the application (our API, for example) previously registered in Keycloak and determines which flows, permissions, and security configurations will be applied.</li><li><strong>Username: </strong>the username registered in Keycloak that is attempting to authenticate.</li><li><strong>Password: </strong>the password of the specified user.</li><li><strong>Client Secret: </strong>used only when the client is of type <strong>confidential</strong>. It acts as the application’s own credential, ensuring that only authorized clients can request tokens.</li></ul><p>Together, these parameters allow Keycloak to validate:</p><ul><li>who the user is,</li><li>which application is requesting access,</li><li>and which authentication flow is being used,</li></ul><p>and then return an access token that can be used to access the protected API endpoints.</p><p><strong>5.2 Creating a user in Keycloak</strong></p><p>If we were using Keycloak’s default frontend, we could enable the registration screen and allow users to sign up themselves. Since we are only testing the API, we will create a user manually.</p><p>In the <strong>Users</strong> menu within the Realm, create a new user by filling in the fields as shown below. Although only the username is mandatory, Keycloak will require the remaining basic information during authentication.</p><figure><img alt="A imagem exibe o formulário de criação de um usuário no portal do Keycloak, contendo campos como nome de usuário, e-mail e demais dados. Além disso, possui os botões de ação para cancelar a criação ou salvar." src="https://cdn-images-1.medium.com/max/1024/1*BcRsagNgvSo-DKIqDOhM6w.png" /><figcaption>Figure 9 — User creation form in Keycloak.</figcaption></figure><p>The password is defined in the <strong>Credentials</strong> tab of the created user. After that, simply fill in the request in Postman with the user and client data, and the access token will be generated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BY7qcFhXemzwOCup8rQNKg.png" /><figcaption>Figure 10 — Authentication response from Keycloak.</figcaption></figure><p>Finally, copy the returned access token and send it in the Authorization header of the request to the API:</p><pre>Authorization: Bearer &lt;access_token&gt;</pre><p>Access will now be granted, and the endpoint will respond correctly:</p><figure><img alt="A imagem exibe um exemplo de requisição no Postman, contendo um formulário com a URL preenchida e o token de acesso. Também é possível ver a resposta da API." src="https://cdn-images-1.medium.com/max/1024/1*sO31uXyRmWDSZ1GA7w9nFQ.png" /><figcaption>Figure 11 — API request with a validated access token.</figcaption></figure><p>This chapter now completes the full cycle:</p><p><strong>Keycloak → token → protected API → validated access.</strong></p><h3>Final considerations</h3><p>The journey was long, but if you made it this far, there is a very good chance that everything is already properly configured and working.</p><p>Of course, this is not a complete guide to Keycloak. In fact, it represents only the beginning of a whole universe of possibilities that the tool offers. The goal here was to build a solid foundation so that you can move forward with more confidence and autonomy from this point on.</p><p>I sincerely hope this content has been useful in some way in your daily work as a developer. If any questions arise, if you have suggestions, or if you simply want to exchange ideas about the topic, feel free to connect with me on <a href="https://www.linkedin.com/in/ronyeri-marinho/"><strong>LinkedIn</strong></a>. I also leave the link to the <a href="https://github.com/ronyeri-marinho/keycloak-spring-xp"><strong>GitHub</strong></a> repository, where the example project used in this article is available.</p><p>Thank you for following along until the end — and see you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8bb3c991bb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internationalization with Spring: A Guide to a Multilingual API]]></title>
            <link>https://medium.com/@ronyerimarinho/internacionaliza%C3%A7%C3%A3o-com-spring-um-guia-para-uma-api-poliglota-3dab6e77a3f3?source=rss-a6315be12acd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dab6e77a3f3</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[internationalization]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Ronyeri Marinho]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 19:05:40 GMT</pubDate>
            <atom:updated>2026-11-07T09:59:15.339Z</atom:updated>
            <content:encoded><![CDATA[<p>Internationalization (commonly abbreviated as i18n) is the process of developing applications, such as APIs, that can be easily adapted to different languages. Its main goal is to make the software’s communication with the user accessible globally, without geographical limitations.</p><blockquote><strong>Fun fact:</strong> “i18n” is formed by combining the first letter of the word “internationalization” with its last letter, separated by the number of characters between them — 18 in total.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQRUxnuZzuo3OROTKTXVzQ.png" /></figure><p>The purpose of this guide is to set up a simple internationalization configuration in a <strong>Spring Boot 3.x</strong> application running on <strong>Java 17</strong>, for those who want to implement custom messages in <strong>bean validations</strong>.</p><p>Here, we’ll build an application from scratch with the minimum number of dependencies required. However, if you’re building on top of an existing Spring Boot application, keep in mind that<strong> you don’t need to add any additional dependencies to work with internationalization</strong>.</p><h3>1. Creating the application</h3><p>To create the application, we used the <a href="https://start.spring.io/">Spring Initializr</a> website, as shown in the image below:</p><figure><img alt="Imagem da tela inicial do Spring Initializr, que contém um formulário com opções de projeto, linguagem, configurações adicionais e dependências a serem utilizadas." src="https://cdn-images-1.medium.com/max/1024/1*haHFrjyiyN38VaUVwv-6Xg.png" /><figcaption>Figure 1 — Spring Initializr home screen</figcaption></figure><p>The dependencies used are, as described below, Spring Web, Spring Boot DevTools, and Validation (Bean validation):</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>       &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>       &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>       &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>       &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;dependency&gt;<br>       &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>       &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;<br>       &lt;scope&gt;runtime&lt;/scope&gt;<br>       &lt;optional&gt;true&lt;/optional&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>       &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>       &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>       &lt;scope&gt;test&lt;/scope&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><h3>2. Configuring internationalization</h3><p>Configuring internationalization so that your Spring application can begin to identify the language to be used involves just a few steps: configuring a bean to specify the <strong>location of the translation files, the encoding, and the default locale.</strong></p><p>You also need to configure the locale resolver, which determines the user’s language preference in their requests based on a header. These settings will be defined in a configuration class, as shown in the example below:</p><pre>package br.com.demo.configuration;<br><br>import jakarta.servlet.http.HttpServletRequest;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;<br><br>import java.util.Arrays;<br>import java.util.List;<br>import java.util.Locale;<br><br>@Configuration<br>public class InternationalizationConfig extends AcceptHeaderLocaleResolver {<br><br>    @Override<br>    public Locale resolveLocale(HttpServletRequest request) {<br>        List&lt;Locale&gt; locales = Arrays.asList(new Locale(&quot;en&quot;), new Locale(&quot;es&quot;), new Locale(&quot;br&quot;));<br>        String headerLanguage = request.getHeader(&quot;Accept-Language&quot;);<br>        return headerLanguage == null || headerLanguage.isEmpty() ? Locale.getDefault()<br>                : Locale.lookup(Locale.LanguageRange.parse(headerLanguage), locales);<br>    }<br><br>    @Bean<br>    ResourceBundleMessageSource messageSource() {<br>        ResourceBundleMessageSource source = new ResourceBundleMessageSource();<br>        source.setBasename(&quot;internationalization/messages&quot;);<br>        source.setDefaultEncoding(StandardCharsets.UTF_8.name());<br>        source.setDefaultLocale(new Locale(&quot;en&quot;));<br>        return source;<br>    }<br>}</pre><p>Here are a few things to explain: First, the class extends AcceptHeaderLocaleResolver, which is part of Spring Web and provides methods for handling internationalization based on the Accept-Language header in HTTP requests.</p><p>Next, we have the overridden resolveLocalemethod, which is where we define the settings mentioned earlier, allowing us to handle different languages based on the header.</p><p>The method defines the supported languages by retrieving the header containing the accepted language, validating it, and returning the content based on the user’s chosen locale (if the user has not specified a locale, the content will be returned based on the default set by the Locale class, as defined in Locale.getDefault()).</p><blockquote>It is important to note that if you already have an existing configuration class that does not extend another class, you can add the above settings to it.</blockquote><p>Following the previous configuration, we begin configuring the <strong>Bean</strong>, which is an instance of ResourceBundleMessageSource — a class in the Spring ecosystem responsible for managing internationalization-related settings. Here, it will be used to configure the path to the translation files, the encoding, and the default locale.</p><p>The setBasename()method is used to define the path and the prefix used before the language names. This is because Spring identifies the translation file for the corresponding language based on a suffix.</p><p>For example, suppose you want the application to support Brazilian Portuguese, English, and Spanish. Your files should follow this pattern:</p><pre>messages_en_US.properties<br>messages_br.properties<br>messages_es.properties</pre><p>However, you may also have a messages.properties file, which would be the default file, regardless of the suffix (language). This file is commonly used to store messages for the application’s default language, and since you are the one doing the translation, you can choose whichever one you want for the default messages.</p><p>A list of available suffixes based on ISO 639–1 can be found <a href="https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes">here</a>.</p><p>Next, we set the encoding to UTF-8, as it is universal and supports a wide variety of characters, preventing encoding issues.</p><p>Finally, we tell the object what the default locale is.</p><h3>3. Creating the translation files</h3><p>Translation files are project property files — that is, files created with the .properties extension, following this structure:</p><figure><img alt="A imagem contém uma estrutura de diretórios, de cima para baixo, contendo src &gt; main &gt; resources &gt; internationalization &gt; messages.properties" src="https://cdn-images-1.medium.com/max/422/1*Gq6gXt_mDoHlHNhScqx6yw.png" /><figcaption>Figure 2 — Application directory structure</figcaption></figure><p>These files follow the <strong>key-value</strong> declaration format, so you enter an identifier for the translation (key) and the message to be translated (value).</p><figure><img alt="Imagem do arquivo de tradução, contendo um único par de chave e valor, especificando uma tradução que informa que um nome não pode ser nulo ou vazio." src="https://cdn-images-1.medium.com/max/1024/1*0mUPVTFtNTzOJhf0o5lOhA.png" /><figcaption>Figure 3 — Translation file</figcaption></figure><p>In this tutorial, I’m creating three translation files (Brazilian Portuguese, English, and Spanish). Remember that the key must be the same in all three files; only the translation value changes based on the language.</p><p><strong>Note:</strong> Instead of creating a new translation key, you can use the translation key contained in the annotation you’re using, as in the example below:</p><figure><img alt="Conteúdo da interface que representa a anotação @NotBlank do Bean Validation." src="https://cdn-images-1.medium.com/max/905/1*jjY0eW8_IfGzPzCw2vSlqw.png" /><figcaption>Figure 4 — Content of the <a href="http://twitter.com/NotBlank">@NotBlank</a> annotation</figcaption></figure><p>The @NotBlank annotation has a translation key, and you can use it in your file to override Spring’s default message.</p><h3>4. Testing our message</h3><p>To test the translation, I’ll create a class that contains a single attribute: the name. I’ll annotate it with @NotBlank and pass our message as a parameter, as follows:</p><pre>package br.com.demo.model;<br><br>import jakarta.validation.constraints.NotBlank;<br><br>public record FooDTO(@NotBlank(message = &quot;{name.not.null.or.blank}&quot;) String name) {<br>    <br>}</pre><p>Since Spring has built-in internationalization, it will automatically retrieve the specified translation key from the configured translation files. This allows you to translate your messages.</p><p>It’s important to note that bean validation annotations already support internationalization in their error messages. So this example can be used in scenarios where you want to customize the messages.</p><p>Now, we need to test whether the messages are actually being captured and returned to the user. To do this, we’ll create a controller that handles a single POST request and receives the previously created class as the request body.</p><pre>package br.com.demo.controller;<br><br>import br.com.demo.model.FooDTO;<br>import jakarta.validation.Valid;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/demo&quot;)<br>public class DemoController {<br><br>    @PostMapping<br>    public ResponseEntity&lt;Void&gt; foo(@RequestBody @Valid FooDTO body) {<br>        return ResponseEntity.ok().build();<br>    }<br>}</pre><p>In Postman, simply create a new request and set the value of the “name” field to null or an empty string:</p><figure><img alt="Screenshot de uma requisição Postman que está sendo usada para testar a implementação." src="https://cdn-images-1.medium.com/max/1024/1*_sWev3WAdP2Es2YSVRDnCw.png" /><figcaption>Figure 5 — Postman request to test the functionality</figcaption></figure><p>We’ll also include the Accept-Language header to specify the language we want to receive:</p><figure><img alt="Screenshot do Postman para exibir qual o cabeçalho da requisição que define o idioma." src="https://cdn-images-1.medium.com/max/1024/1*QSFZPiCvhDDxuUuz9WUu2w.png" /><figcaption>Figure 6 — Postman request header that sets the language</figcaption></figure><p>When we send the request, we receive the following response:</p><pre>{<br>    &quot;timestamp&quot;: &quot;2023-10-20T17:58:59.320+00:00&quot;,<br>    &quot;status&quot;: 400,<br>    &quot;error&quot;: &quot;Bad Request&quot;,<br>    &quot;trace&quot;: &quot;org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity&lt;java.lang.Void&gt; br.com.demo.controller.DemoController.foo(br.com.demo.model.FooDTO): [Field error in object &#39;fooDTO&#39; on field &#39;name&#39;: rejected value []; codes [NotBlank.fooDTO.name,NotBlank.name,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [fooDTO.name,name]; arguments []; default message [name]]; default message [O nome não pode ser nulo ou vazio]] \n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:144)\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:122)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179)\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146)\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1081)\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:974)\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011)\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:914)\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:894)\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1740)\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n\tat java.base/java.lang.Thread.run(Thread.java:833)\n&quot;,<br>    &quot;message&quot;: &quot;Validation failed for object=&#39;fooDTO&#39;. Error count: 1&quot;,<br>    &quot;errors&quot;: [<br>        {<br>            &quot;codes&quot;: [<br>                &quot;NotBlank.fooDTO.name&quot;,<br>                &quot;NotBlank.name&quot;,<br>                &quot;NotBlank.java.lang.String&quot;,<br>                &quot;NotBlank&quot;<br>            ],<br>            &quot;arguments&quot;: [<br>                {<br>                    &quot;codes&quot;: [<br>                        &quot;fooDTO.name&quot;,<br>                        &quot;name&quot;<br>                    ],<br>                    &quot;arguments&quot;: null,<br>                    &quot;defaultMessage&quot;: &quot;name&quot;,<br>                    &quot;code&quot;: &quot;name&quot;<br>                }<br>            ],<br>            &quot;defaultMessage&quot;: &quot;O nome não pode ser nulo ou vazio&quot;, // FUNCIONOU!!<br>            &quot;objectName&quot;: &quot;fooDTO&quot;,<br>            &quot;field&quot;: &quot;name&quot;,<br>            &quot;rejectedValue&quot;: &quot;&quot;,<br>            &quot;bindingFailure&quot;: false,<br>            &quot;code&quot;: &quot;NotBlank&quot;<br>        }<br>    ],<br>    &quot;path&quot;: &quot;/demo&quot;<br>}</pre><p>Well, the feedback is working correctly. However, we can improve the feedback a little so that we get only what’s important to us:</p><pre>package br.com.demo.controller;<br><br>import jakarta.servlet.http.HttpServletRequest;<br>import org.springframework.http.HttpStatus;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.validation.BindingResult;<br>import org.springframework.validation.ObjectError;<br>import org.springframework.web.bind.MethodArgumentNotValidException;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.RestControllerAdvice;<br><br>@RestControllerAdvice<br>public class ControllerExceptionHandler {<br><br>    @ExceptionHandler(MethodArgumentNotValidException.class)<br>    protected ResponseEntity&lt;String&gt; handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {<br>        StringBuilder messages = new StringBuilder();<br>        BindingResult bindingResult = e.getBindingResult();<br><br>        bindingResult.getFieldErrors().forEach(error -&gt; {<br>            messages.append(error.getDefaultMessage()).append(&quot; \n&quot;);<br>        });<br>        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(messages.toString());<br>    }<br>}</pre><p>We’ve created a class annotated with @RestControllerAdvice that will handle exception handling globally for our controllers. In addition, we’ve created a method that handles MethodArgumentNotValidExeption, which is the exception thrown by bean validations. This allows us to implement custom exception handling.</p><p>What we do here in the body of the method is simply retrieve the BindingResult object — which contains detailed error information — iterate through the field errors (FieldErrors), and concatenate the messages together, separating them with a line break.</p><p>Finally, we return a response with the appropriate HTTP status and our messages. The result is as follows:</p><ol><li>For Brazilian Portuguese:</li></ol><figure><img alt="Resultado da requisição Postman em português brasileiro." src="https://cdn-images-1.medium.com/max/1024/1*Ze5mElUFDZkOzVeV7x6M2g.png" /><figcaption>Figure 7 — Request result for Brazilian Portuguese.</figcaption></figure><p>2. For English:</p><figure><img alt="Resultado da requisição Postman em inglês." src="https://cdn-images-1.medium.com/max/1024/1*a7BA9KQKqsWLUlLjRl3JaQ.png" /><figcaption>Figure 8— Request result for English.</figcaption></figure><p>3. For Spanish:</p><figure><img alt="Resultado da requisição Postman em espanhol." src="https://cdn-images-1.medium.com/max/1024/1*MMnBGvcjdI1vJ7VfH13Qrg.png" /><figcaption>Figure 9— Request result for Spanish.</figcaption></figure><h3>Concluding Remarks</h3><p>Internationalization is an important part of building modern systems, promoting greater inclusivity for different regions and languages, as well as ensuring compliance with language requirements when necessary. With that in mind, I hope this guide helps you make your applications multilingual.</p><p>If you have any questions, suggestions, or feedback, please feel free to <a href="https://www.linkedin.com/in/ronyeri-marinho/">contact me</a>. The code developed in this tutorial is available on <a href="https://github.com/ronny-souza/internationalization-xp">GitHub</a>.</p><p>Thank you for reading this far!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dab6e77a3f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>