<?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 Rajithaubandara on Medium]]></title>
        <description><![CDATA[Stories by Rajithaubandara on Medium]]></description>
        <link>https://medium.com/@rajithaubandara?source=rss-cb143e93805f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Izu3ZxuACZpxEXvejTFMrA.jpeg</url>
            <title>Stories by Rajithaubandara on Medium</title>
            <link>https://medium.com/@rajithaubandara?source=rss-cb143e93805f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:00:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajithaubandara/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[Securing a Spring Boot 3 REST API with Keycloak]]></title>
            <link>https://medium.com/@rajithaubandara/securing-a-spring-boot-3-rest-api-with-keycloak-f9c21c6e1fd4?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9c21c6e1fd4</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 09:23:03 GMT</pubDate>
            <atom:updated>2026-04-23T09:23:03.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*hFCQfxwhA0H9TkNYS67F2g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*cYBqdVaG8JZzgmqmuJ4DRA.png" /></figure><p>When building modern APIs, delegating authentication and authorization to a dedicated Identity Provider (IdP) like Keycloak is a standard practice. In this post, we will walk through a Spring Boot project that acts as an OAuth2 Resource Server, secured by a local Keycloak instance.</p><h3>Project Overview</h3><p>This project is a Java 21 application built using Spring Boot version 3.5.13. It leverages the spring-boot-starter-oauth2-resource-server and spring-boot-starter-security dependencies to protect its REST endpoints.</p><p>For the identity provider, the project uses a Dockerized instance of Keycloak (version 26.6.1) running in development mode (start-dev). The Spring Boot application is configured to run on port 8081, while Keycloak runs on port 8080.</p><h3>Objective</h3><p>The main objective of this project is to implement stateless, Role-Based Access Control (RBAC) using JSON Web Tokens (JWTs) issued by Keycloak.</p><p>By default, Spring Security doesn’t know how to read Keycloak’s deeply nested client roles. To solve this, the project implements a custom JWTAuthConverter that intercepts the JWT, looks inside the resource_access claim for a specific resource ID (rajitha-rest-api), and maps those specific roles into Spring Security GrantedAuthority objects (prefixed with ROLE_).</p><h3>Inputs &amp; Required Outputs</h3><p>To successfully interact with the secured API, the client must provide a Bearer Token (JWT) in the Authorization header. Depending on the role extracted from the provided JWT, the API will respond differently:</p><ul><li><strong>With the </strong><strong>admin role:</strong> * <strong>Request:</strong> GET /api/v1/demo/hello-1 (Secured by @PreAuthorize(&quot;hasRole(&#39;admin&#39;)&quot;))</li><li><strong>Output:</strong> &quot;Hello from spring boot and keycloak user&quot;</li><li><strong>With the </strong><strong>user role:</strong></li><li><strong>Request:</strong> GET /api/v1/demo/hello-2 (Secured by @PreAuthorize(&quot;hasRole(&#39;user&#39;)&quot;))</li><li><strong>Output:</strong> &quot;Hello2 from spring boot and keycloak admin</li></ul><p>If a request is made without a token, or with a token lacking the appropriate roles mapped to rajitha-rest-api, the server will return a 401 Unauthorized or 403 Forbidden.</p><h3>How to Build</h3><p>To compile the Java 21 codebase and resolve all dependencies, open your terminal at the project root and run the included Maven wrapper:</p><p>Bash</p><pre>./mvnw clean compile</pre><h3>How to Run &amp; Configure the System</h3><p>To get the full system running, you must start Keycloak, configure the required Realm and Client with the correct authentication flows, and then start the Spring Boot app.</p><h4>1. Start the Keycloak Server</h4><p>The project includes a docker-compose.yml file. Spin up the Keycloak container:</p><p>Bash</p><pre>docker-compose up -d</pre><p>Keycloak will start on http://127.0.0.1:8080 with the initial credentials: admin / admin.</p><h4>2. Configure Keycloak (Realm, Client, and Roles)</h4><p>Your Spring Boot application specifically looks for a realm named rajitha_realm and a client named rajitha-rest-api. You must configure these manually in the Keycloak Admin Console:</p><ul><li><strong>Log in:</strong> Go to http://localhost:8080 and click &quot;Administration Console&quot;. Log in with admin / admin.</li><li><strong>Create the Realm:</strong> * Click the Keycloak dropdown in the top left and select <strong>Create Realm</strong>.</li><li>Set the <strong>Realm name</strong> to exactly rajitha_realm and click Create.</li><li><strong>Create and Configure the Client:</strong></li><li>Make sure you are in rajitha_realm. Go to <strong>Clients</strong> -&gt; <strong>Create client</strong>.</li><li>Set the <strong>Client ID</strong> to exactly rajitha-rest-api. Click Next.</li><li><strong>Capability config:</strong> * Leave <strong>Client authentication</strong> toggled <strong>Off</strong> (This makes it a Public client, which is usually easiest for testing via Postman or a SPA frontend).</li><li>Ensure <strong>Standard flow</strong> is checked.</li><li><strong>CRITICAL:</strong> Check <strong>Direct access grants</strong>. (This enables the Password Grant type, allowing you to easily generate tokens in Postman using just a username and password). Click Next.</li><li><strong>Login settings:</strong> * Set <strong>Valid redirect URIs</strong> to * (or your specific Postman callback URL like https://oauth.pstmn.io/v1/callback if testing strictly).</li><li>Set <strong>Web origins</strong> to * (to prevent CORS issues during testing).</li><li>Click Save.</li><li><strong>Create Client Roles:</strong></li><li>Go to the <strong>Roles</strong> tab (inside your rajitha-rest-api client settings).</li><li>Click <strong>Create role</strong>. Create a role named admin.</li><li>Create another role named user.</li><li><strong>Create a Test User:</strong></li><li>Go to <strong>Users</strong> -&gt; <strong>Add user</strong>. Set a username (e.g., testuser). Click Create.</li><li>Go to the <strong>Credentials</strong> tab for that user, click <strong>Set password</strong>, enter a password, and toggle “Temporary” to OFF.</li><li><strong>Assign Roles to the User:</strong></li><li>Still on the user’s page, go to the <strong>Role mapping</strong> tab.</li><li>Click <strong>Assign role</strong>. Filter by <strong>Filter by clients</strong>.</li><li>Select the admin and/or user roles belonging to rajitha-rest-api and assign them</li></ul><p><em>(Note: Because of how Keycloak works out-of-the-box, assigning a client role ensures it will appear in the JWT under the </em><em>resource_access.rajitha-rest-api.roles claim, which perfectly matches the logic in your </em><em>JWTAuthConverter.)</em></p><h4>3. Start the Spring Boot Application</h4><p>Once Keycloak is fully configured, start the Spring Boot app so it can connect to the Keycloak JWKS endpoint to validate tokens:</p><p>Bash</p><pre>./mvnw spring-boot:run</pre><p>The application will start on port 8081.</p><h4>4. Run the Tests</h4><p>To test that your Role-Based Access Control (RBAC) is working properly, you will need to perform a two-step process for each test: first, request a JWT (Access Token) from Keycloak, and second, use that token to make a request to your Spring Boot API.</p><p>For these tests, we will assume you have created <strong>two different users</strong> in your Keycloak rajitha_realm under the rajitha-rest-api client:</p><ol><li><strong>User 1:</strong> Username admin_user with password password (Assigned the admin role).</li><li><strong>User 2:</strong> Username standard_user with password password (Assigned the user role).</li></ol><p>Here is how to test the API calls using standard curl commands (which you can also replicate exactly in Postman).</p><h4>Test Scenario 1: Testing as the Admin</h4><p><strong>Step 1: Get the Admin Token</strong></p><p>Run this command in your terminal to ask Keycloak for an access token using the admin_user credentials.</p><p>Bash</p><pre>curl -X POST &quot;http://localhost:8080/realms/rajitha_realm/protocol/openid-connect/token&quot; \<br>     -H &quot;Content-Type: application/x-www-form-urlencoded&quot; \<br>     -d &quot;client_id=rajitha-rest-api&quot; \<br>     -d &quot;username=admin_user&quot; \<br>     -d &quot;password=password&quot; \<br>     -d &quot;grant_type=password&quot;</pre><p><em>Keycloak will return a large JSON response. Copy the long string inside the </em><em>&quot;access_token&quot;: &quot;eyJhbGciOiJSUz... field.</em></p><p><strong>Step 2: Access the Admin API (Success Expected)</strong></p><p>Use the copied token to call the /hello-1 endpoint, which requires the admin role.</p><p>Bash</p><pre>curl -X GET &quot;http://localhost:8081/api/v1/demo/hello-1&quot; \<br>     -H &quot;Authorization: Bearer &lt;PASTE_ADMIN_TOKEN_HERE&gt;&quot;</pre><ul><li><strong>Expected Result:</strong> 200 OK</li><li><strong>Output:</strong> Hello from spring boot and keycloak user</li></ul><p><strong>Step 3: Try to Access the User API (Failure Expected)</strong></p><p>Use the exact same admin token to try and access the /hello-2 endpoint, which requires the user role.</p><p>Bash</p><pre>curl -i -X GET &quot;http://localhost:8081/api/v1/demo/hello-2&quot; \<br>     -H &quot;Authorization: Bearer &lt;PASTE_ADMIN_TOKEN_HERE&gt;&quot;</pre><ul><li><strong>Expected Result:</strong> 403 Forbidden (Because the admin_user does not possess the user role).</li></ul><h4>Test Scenario 2: Testing as the Standard User</h4><p><strong>Step 1: Get the User Token</strong></p><p>Request a new token from Keycloak, this time using the standard_user credentials.</p><p>Bash</p><pre>curl -X POST &quot;http://localhost:8080/realms/rajitha_realm/protocol/openid-connect/token&quot; \<br>     -H &quot;Content-Type: application/x-www-form-urlencoded&quot; \<br>     -d &quot;client_id=rajitha-rest-api&quot; \<br>     -d &quot;username=standard_user&quot; \<br>     -d &quot;password=password&quot; \<br>     -d &quot;grant_type=password&quot;</pre><p><em>Copy the new </em><em>&quot;access_token&quot; string from the response.</em></p><p><strong>Step 2: Access the User API (Success Expected)</strong></p><p>Call the /hello-2 endpoint, which requires the user role.</p><p>Bash</p><pre>curl -X GET &quot;http://localhost:8081/api/v1/demo/hello-2&quot; \<br>     -H &quot;Authorization: Bearer &lt;PASTE_USER_TOKEN_HERE&gt;&quot;</pre><ul><li><strong>Expected Result:</strong> 200 OK</li><li><strong>Output:</strong> Hello2 from spring boot and keycloak admin</li></ul><p><strong>Step 3: Try to Access the Admin API (Failure Expected)</strong></p><p>Use the standard user token to try and access the /hello-1 endpoint.</p><p>Bash</p><pre>curl -i -X GET &quot;http://localhost:8081/api/v1/demo/hello-1&quot; \<br>     -H &quot;Authorization: Bearer &lt;PASTE_USER_TOKEN_HERE&gt;&quot;</pre><ul><li><strong>Expected Result:</strong> 403 Forbidden (Because the standard_user does not possess the admin role, Spring Security intercepts and blocks the request before it ever reaches the controller).</li></ul><h3>How to do this in Postman:</h3><p>If you prefer Postman over curl:</p><ul><li><strong>To get the token:</strong> Create a new POST request to http://localhost:8080/realms/rajitha_realm/protocol/openid-connect/token. Go to the <strong>Body</strong> tab, select x-www-form-urlencoded, and add the keys: client_id (value: rajitha-rest-api), username (value: admin_user), password (value: password), and grant_type (value: password). Click Send.</li><li><strong>To hit the API:</strong> Create a new GET request to http://localhost:8081/api/v1/demo/hello-1. Go to the <strong>Authorization</strong> tab, select <strong>Bearer Token</strong> from the dropdown, paste the token from step 1 into the Token field, and click Send.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9c21c6e1fd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Streaming Monitor Project]]></title>
            <link>https://medium.com/@rajithaubandara/kafka-streaming-monitor-project-66c9c54dfe20?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/66c9c54dfe20</guid>
            <category><![CDATA[webclient]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 07:59:16 GMT</pubDate>
            <atom:updated>2026-04-23T07:59:16.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MAsS03NVIxzBQXu3oMWVw.png" /></figure><h3><strong>A Simple Blog About the Project</strong></h3><p>This project is a small real-time Kafka demo that shows how two Spring Boot services can work together with streaming data. The producer reads Wikimedia recent-change events, sends them into Kafka, and the consumer forwards the messages to a browser-based live monitor.</p><p>What makes it useful is the full flow:</p><p>1. A request starts the producer at `http://localhost:8010/api/v1/wikimedia`.</p><p>2. The producer reads the Wikimedia stream from `https://stream.wikimedia.org/v2/stream/recentchange`.</p><p>3. Kafka passes the messages to the consumer service.</p><p>4. The browser UI shows the incoming events in real time.</p><p>The project is designed to be easy to run on Windows. The `windows_run-all.cmd` script builds both Spring Boot apps, starts Docker Compose, and opens the monitor page automatically. The UI also checks readiness and starts the stream when the containers are available.</p><h3><strong>How to Run</strong></h3><p>From the repository root on Windows:</p><p><em>powershell</em></p><p><em>./windows_run-all.cmd</em></p><p>Open the monitor page here: [display/DisplayUI.html](display/DisplayUI.html)</p><p>Stop everything only with:</p><p><em>powershell</em></p><p><em>docker compose down</em></p><h3><strong>What You Will See</strong></h3><p>When the stack is ready, the page shows the container status and then starts displaying Wikimedia events as they arrive through Kafka.</p><h3><strong>Short Summary</strong></h3><p>This project demonstrates simple streaming architecture with:</p><p>1. Spring Boot producer</p><p>2. Kafka message transport</p><p>3. Spring Boot consumer</p><p>4. Live HTML event dashboard</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66c9c54dfe20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How BOM (Bill of Materials) Saves Your Spring Boot Microservices from Dependency Hell]]></title>
            <link>https://medium.com/@rajithaubandara/how-bom-bill-of-materials-saves-your-spring-boot-microservices-from-dependency-hell-82334e15a22a?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/82334e15a22a</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[maven]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 09:42:20 GMT</pubDate>
            <atom:updated>2026-03-27T12:55:40.136Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In modern microservices architectures, managing dependencies across multiple services quickly becomes complex. You may add a new dependency, everything compiles successfully, tests pass and then your application crashes at runtime.</p><p>This is where <strong>BOM (Bill of Materials)</strong> becomes critical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*XtVf-4lOHRl9I0VO.jpg" /></figure><h3>What is BOM in Maven?</h3><p>A <strong>BOM (Bill of Materials)</strong> is a special Maven POM file that centralizes and manages dependency versions using the &lt;dependencyManagement&gt; section.</p><p>Instead of defining versions in every microservice:</p><pre>&lt;version&gt;3.3.0&lt;/version&gt;</pre><p>You define them once in a BOM and reuse across services.</p><h3>The Problem BOM Solves</h3><p>In a microservices system:</p><ul><li>Each service has its own pom.xml</li><li>Dependencies bring <strong>transitive dependencies</strong></li><li>Different services may use different versions</li></ul><h3>Typical Issues</h3><ul><li>Runtime crashes due to version mismatch</li><li>Hidden conflicts (compile success, runtime failure)</li><li>Inconsistent environments across services</li><li>Difficult debugging</li></ul><h3>Example Problem</h3><pre>Service A → Spring Cloud 2022.0.1  <br>Service B → Spring Cloud 2022.0.0  </pre><pre>Feign / Gateway mismatch → Runtime failure</pre><h3>How BOM Solves This</h3><p>BOM enforces <strong>version consistency</strong> across all services.</p><h3>Mechanism</h3><ul><li>Define versions centrally</li><li>Import BOM into each microservice</li><li>Remove version tags from dependencies</li></ul><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;2022.0.1&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><h3>Two Types of BOM Usage in Microservices</h3><h3>1. Service Level BOM</h3><p>Each microservice manages its own dependency versions.</p><h3>Use Case</h3><ul><li>Independent teams</li><li>Experimental services</li><li>Different tech stacks per service</li></ul><h3>Example</h3><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;3.3.0&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><h3>Result</h3><ul><li>Full control per service</li><li>Risk of version drift</li></ul><h3>2. Common (Centralized) BOM</h3><p>A shared BOM is used across all microservices.</p><h3>Use Case</h3><ul><li>Large scale microservices architecture</li><li>Need strict version consistency</li><li>Shared infrastructure (Kafka, DB, Gateway, etc.)</li></ul><h3>Example Structure</h3><pre>company-bom/<br>product-service/<br>order-service/<br>notification-service/</pre><h3>BOM Example</h3><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;3.3.0&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><h3>Sample Microservice Module Setup</h3><h3>Project Structure</h3><pre>microservices-repo/<br> ├─ company-bom/<br> ├─ product-service/<br> ├─ order-service/<br> └─ notification-service/</pre><h3>BOM POM</h3><pre>&lt;project&gt;<br>    &lt;groupId&gt;com.example&lt;/groupId&gt;<br>    &lt;artifactId&gt;company-bom&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>    &lt;packaging&gt;pom&lt;/packaging&gt;</pre><pre>    &lt;dependencyManagement&gt;<br>        &lt;dependencies&gt;<br>            &lt;dependency&gt;<br>                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>                &lt;artifactId&gt;spring-boot-dependencies&lt;/artifactId&gt;<br>                &lt;version&gt;3.3.0&lt;/version&gt;<br>                &lt;type&gt;pom&lt;/type&gt;<br>                &lt;scope&gt;import&lt;/scope&gt;<br>            &lt;/dependency&gt;</pre><pre>            &lt;dependency&gt;<br>                &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>                &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>                &lt;version&gt;2022.0.1&lt;/version&gt;<br>                &lt;type&gt;pom&lt;/type&gt;<br>                &lt;scope&gt;import&lt;/scope&gt;<br>            &lt;/dependency&gt;<br>        &lt;/dependencies&gt;<br>    &lt;/dependencyManagement&gt;<br>&lt;/project&gt;</pre><h3>Product Service POM</h3><pre>&lt;project&gt;<br>    &lt;parent&gt;<br>        &lt;groupId&gt;com.example&lt;/groupId&gt;<br>        &lt;artifactId&gt;company-bom&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.0&lt;/version&gt;<br>    &lt;/parent&gt;</pre><pre>    &lt;artifactId&gt;product-service&lt;/artifactId&gt;</pre><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-web&lt;/artifactId&gt;<br>        &lt;/dependency&gt;</pre><pre>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-starter-openfeign&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/project&gt;</pre><h3>Result of Using BOM</h3><p>After implementing BOM:</p><ul><li>All services use <strong>consistent dependency versions</strong></li><li>No more hidden runtime conflicts</li><li>Easier upgrades (change BOM version once)</li><li>Cleaner pom.xml files</li></ul><h3>Pros and Cons</h3><h3>Advantages</h3><ul><li>Centralized dependency management</li><li>Eliminates version conflicts</li><li>Improves system stability</li><li>Cleaner and maintainable POM files</li><li>Easy upgrades across services</li></ul><h3>Disadvantages</h3><ul><li>Less flexibility for individual services</li><li>Requires coordination when updating BOM</li><li>Incorrect BOM version can impact all services</li></ul><h3>Best Practices</h3><ul><li>Use <strong>Spring Boot + Spring Cloud BOM together</strong></li><li>Keep BOM versioned (e.g., 1.0.0, 1.1.0)</li><li>Validate dependencies using:</li></ul><pre>mvn dependency:tree</pre><ul><li>Use centralized BOM for production systems</li><li>Use service level BOM only for special cases</li></ul><h3>Conclusion</h3><p>BOM is not just a convenience it is essential for maintaining <strong>stability, consistency, and scalability</strong> in microservices architectures.</p><p>Without BOM, dependency conflicts are inevitable.<br>With BOM, your system becomes predictable, maintainable, and production-ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82334e15a22a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a BOM Saved My Spring Boot Microservices Project from Collapse]]></title>
            <link>https://medium.com/@rajithaubandara/how-a-bom-saved-my-spring-boot-microservices-project-from-collapse-1aa70c8be72d?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa70c8be72d</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 09:06:39 GMT</pubDate>
            <atom:updated>2026-03-27T09:45:19.680Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comprehensive guide to managing transitive dependency conflicts and avoiding runtime crashes in Java microservices.</h4><p>Imagine this common scenario you are scaling a Spring Boot microservices architecture. You decide to introduce a new component perhaps an API Gateway, a Circuit Breaker, or a centralized Configuration server.</p><p>Adding the dependency seems straightforward. You update the pom.xml, run a quick mvn clean install, and the build passes without a single warning. The unit tests are green. Everything looks ready for production.</p><p>Then, the application is deployed, and it immediately falls apart at runtime.</p><h3>The False Sense of Security</h3><p>The build succeeds, but the moment the service starts, it throws errors that point nowhere obvious. This is a notorious trap in Java dependency management a passing build does not guarantee a functioning runtime classpath.</p><h3>The Problem Build Passes, Runtime Crashes</h3><p>Often, within seconds of starting a newly updated service, the console will erupt with stack traces. The most common culprits are NoSuchMethodError and ClassNotFoundException involving core library classes.</p><p>Both errors point to classes that absolutely exist on the classpath just not in the versions the runtime expected.</p><p><strong>Common Runtime Errors:</strong></p><pre>java.lang.NoSuchMethodError:<br>org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer.choose(Object)<br>java.lang.ClassNotFoundException:<br>org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient</pre><p>What makes this particularly frustrating is the <strong>transitive dependency(Derectly aded dependency for project) mismatch</strong>. When a library like Spring Cloud Gateway is added, it pulls in its own versions of several sub components. These versions can quietly conflict with what Spring Boot has already resolved elsewhere.</p><p>This is the hidden danger of microservices dependency management Maven resolves conflicts silently using ‘nearest definition’ rules. The “winning” version may be completely incompatible with another library expecting a different API contract.</p><blockquote><strong><em>Root Cause Pattern:</em></strong><em> </em><em>NoSuchMethodError and </em><em>ClassNotFoundException at runtime with a successful build is almost always a version conflict. The class exists, but the method signature or class structure changed between versions.</em></blockquote><h3>Investigation Following the Dependency Tree</h3><p>When these errors occur, the best diagnostic tool is mvn dependency:tree. This command outputs the entire resolved dependency graph for the project, revealing the hidden conflicts.</p><pre>$ mvn dependency:tree | grep spring-cloud<br># Conflicting versions detected:<br>[INFO] +- org.springframework.cloud:spring-cloud-gateway-core:jar:3.1.4:compile<br>[INFO] \- org.springframework.cloud:spring-cloud-commons:jar:3.0.1:compile &lt;- conflict!<br>[INFO] \- org.springframework.cloud:spring-cloud-loadbalancer:jar:3.1.4:compile &lt;- different minor!</pre><p>This generic output reveals that multiple modules within the same ecosystem (like Spring Cloud) are resolving to different patch and minor versions. In this example, spring-cloud-commons is at 3.0.1 while spring-cloud-gateway-core is at 3.1.4 combinations that are often strictly incompatible.</p><p>The root cause is clear adding a high level dependency without telling Maven <em>which</em> overarching version of the ecosystem to use forces Maven to pick versions independently for each transitive dependency.</p><h3>Solution Discovery: The Bill of Materials (BOM)</h3><p>The robust solution to this architectural challenge is a <strong>BOM (Bill of Materials)</strong>.</p><p>A BOM is a special POM file that defines a curated, tested set of dependency versions. Instead of declaring individual versions for every library you use, you import the BOM and let it govern all version decisions for that ecosystem.</p><p>Spring Cloud, for instance, publishes exactly this: spring-cloud-dependencies. This BOM aligns every Spring Cloud module to versions that are tested and guaranteed to work together alongside a specific Spring Boot release.</p><blockquote><strong><em>Key Insight:</em></strong><em> Spring Boot already ships with its own dependency BOM (</em><em>spring-boot-dependencies), which manages core Spring and third-party libraries. However, major extensions like Spring Cloud or AWS SDKs are separate projects—they require their own explicit BOM imports to ensure full compatibility.</em></blockquote><h3>Implementation: Adding the BOM</h3><p>The fix requires adding a &lt;dependencyManagement&gt; block to the root pom.xml. This is distinctly different from the regular &lt;dependencies&gt; block—it declares version constraints and rules without actually downloading the jars.</p><p><strong>The Proper Architecture (</strong><strong>pom.xml):</strong></p><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;!-- 1. Import the BOM here --&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;2023.0.1&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;<br>&lt;dependencies&gt;<br>    &lt;!-- 2. Declare dependencies WITHOUT versions! --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-cloud-starter-gateway&lt;/artifactId&gt;<br>        &lt;!-- No &lt;version&gt; tag needed --&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>Notice that after adding the BOM, individual Spring Cloud dependencies no longer need a &lt;version&gt; tag. The BOM acts as the single source of truth. Manually overriding a version in the &lt;dependencies&gt; block after importing a BOM defeats the purpose and reintroduces instability.</p><blockquote>For more about BOM come to <a href="https://medium.com/@rajithaubandara/how-bom-bill-of-materials-saves-your-spring-boot-microservices-from-dependency-hell-82334e15a22a">Part 2(Click this)</a></blockquote><h3>Version Compatibility Reference</h3><p>Always verify compatibility matrices before choosing a BOM version. For Spring, the release trains strictly align</p><h3>How the BOM Solves the Problem</h3><p>Importing the BOM standardizes your build process by achieving the following simultaneously:</p><ol><li><strong>Aligns all ecosystem components:</strong> Every module (Gateway, Load Balancer, Config, Eureka) resolves to versions that were integration-tested together by the maintainers.</li><li><strong>Ensures framework compatibility:</strong> Each BOM release is mapped to a specific base framework generation.</li><li><strong>Controls transitive dependencies:</strong> Maven’s dependency mediation now uses the BOM-specified versions as the baseline. Deep transitive pulls no longer “win” with arbitrary or outdated versions.</li><li><strong>Removes manual version management:</strong> You declare artifacts without version tags, keeping your pom.xml clean and making upgrades as simple as changing one line.</li><li><strong>Prevents runtime surprises:</strong> NoSuchMethodError and ClassNotFoundException disappear because all components share a strictly enforced, consistent API contract.</li></ol><h3>Before vs. After</h3><h4>Without BOM</h4><p><em>Different patch versions of the same module</em></p><p><em>Fragile and unpredictable builds</em></p><h4>With BOM</h4><p><em>Single BOM import governs all versions</em></p><p><em>All components share one API version</em></p><p><em>Zero manual version declarations</em></p><h3>Key Takeaways</h3><ol><li><strong>Always import the ecosystem BOM:</strong> Never add vast ecosystem dependencies (Spring Cloud, AWS, GCP libraries) without first importing their official BOM in dependencyManagement.</li><li><strong>Never mix random versions:</strong> Copying a version number from a blog post or Stack Overflow answer without checking the compatibility matrix is a recipe for runtime failures.</li><li><strong>Understand </strong><strong>dependencyManagement:</strong> This block is specifically for establishing version constraints, not for pulling in artifacts directly.</li><li><strong>Debug with </strong><strong>mvn dependency:tree:</strong> When something breaks at runtime, map your dependency tree before looking at code. Multiple versions of the same artifact are the first red flag.</li><li><strong>Match BOMs to your core framework:</strong> Ensure your BOM release train is tied exactly to your base framework’s generation.</li></ol><h3>Conclusion</h3><p>Dependency management in enterprise Java is critical infrastructure work. A single missing BOM import can result in hours of debugging, staging rollbacks, and unnecessary stress.</p><p>The BOM pattern is the stability layer of any modern Java project. It represents a contract: <em>these versions were tested together, and they are guaranteed to work together</em>. Without it, developers rely on Maven’s default conflict resolution algorithm to make decisions it was never designed to make correctly for complex, interconnected ecosystems.</p><p>When combining multi library ecosystems, always ask <strong>is there a BOM for this?</strong> If yes, import it before anything else. That one block of XML is worth its weight in stable deployments.</p><blockquote><strong><em>Final Principle:</em></strong><em> The BOM is not optional for complex ecosystems. It is the foundation. Import it first, version nothing manually, and let the maintainers’ compatibility testing work for you.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa70c8be72d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ansible Components]]></title>
            <link>https://medium.com/@rajithaubandara/ansible-components-b6463ee79a90?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6463ee79a90</guid>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Sun, 18 Jan 2026 03:17:42 GMT</pubDate>
            <atom:updated>2026-01-18T03:47:09.479Z</atom:updated>
            <content:encoded><![CDATA[<p>Ansible is an open-source automation tool used for IT tasks such as configuration management, application deployment, and intra-service orchestration. It allows you to define your infrastructure as code (IaC), ensuring consistency across your servers without manual intervention.</p><p>Below is a breakdown of the core components you need to understand to start using Ansible effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bhjyLre0QSOZzfzwr2jBA.png" /></figure><h3>1. Inventory: The Managed Nodes List</h3><p><strong>Concept:</strong> The <strong>Inventory</strong> is the foundation of Ansible. It is a text file (often formatted as INI or YAML) that lists the IP addresses or hostnames of the servers (nodes) you want to manage. It allows you to organize servers into logical groups, such as “webservers” or “databases,” so you can target specific sets of infrastructure.</p><p><strong>Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2l5hXw5xbsT4ruVRSsuNw.png" /></figure><p><strong>Sample Code (</strong><strong>hosts.ini):</strong></p><pre>[webservers]<br>web1.example.com<br>web2.example.com<br><br>[db_servers]<br>db1.example.com</pre><h3>2. Playbook: The Automation Script</h3><p><strong>Concept:</strong> A <strong>Playbook</strong> is a file written in <strong>YAML</strong> that describes the desired state of your system. Unlike a shell script that runs commands sequentially, an Ansible playbook declares <em>what</em> the configuration should look like. Ansible ensures the system matches this state.</p><p><strong>Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_G8-gKHK7uXTqTYMWGhirQ.png" /></figure><p><strong>Sample Code (</strong><strong>install_web.yml):</strong></p><pre>---<br>- name: Setup Web Server<br>  hosts: webservers  # Targets the group defined in Inventory<br>  become: yes        # Executes commands with sudo/root privileges<br><br>  tasks:<br>    - name: Install Nginx<br>      apt:<br>        name: nginx<br>        state: present<br><br>    - name: Start Nginx Service<br>      service:<br>        name: nginx<br>        state: started</pre><h3>3. Variables: Dynamic Configuration</h3><p><strong>Concept:</strong> <strong>Variables</strong> allow you to make your playbooks dynamic and reusable. Instead of hardcoding values (like port numbers, file paths, or usernames), you use variables. This allows you to use the same playbook across different environments (e.g., Development vs. Production) by simply changing the variable values.</p><p><strong>Sample Code:</strong></p><pre>vars:<br>  http_port: 8080<br>  server_name: &quot;MyDevOpsBlog&quot;<br><br>tasks:<br>  - name: Configure Port<br>    lineinfile:<br>      path: /etc/nginx/nginx.conf<br>      line: &quot;listen {{ http_port }};&quot; # Variable interpolation</pre><h3>4. Roles: Modularization and Structure</h3><p><strong>Concept:</strong> As infrastructure complexity grows, single playbook files become difficult to maintain. <strong>Roles</strong> provide a way to load tasks, variables, and handlers automatically based on a known file structure. They allow you to break down complex configurations into smaller, reusable components.</p><p><strong>ASCII (Standard Directory Structure):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zh-3XoeLBSJI-5P7QJbXEQ.png" /></figure><p><strong>Use Case:</strong> You can create a general security role that applies basic firewall rules and user accounts, and reuse that role across every project you manage.</p><h3>5. Master Playbook: Orchestration</h3><p><strong>Concept:</strong> The <strong>Master Playbook</strong> (often named site.yml or main.yml) acts as the entry point for your automation. It does not usually contain specific tasks. Instead, it maps groups of servers (from the Inventory) to the specific Roles they require.</p><p><strong>Sample Code (</strong><strong>site.yml):</strong></p><pre>---<br>- name: Configure Base System<br>  hosts: all<br>  roles:<br>    - common_security<br><br>- name: Configure Web Tier<br>  hosts: webservers<br>  roles:<br>    - nginx_role<br><br>- name: Configure Database Tier<br>  hosts: db_servers<br>  roles:<br>    - mysql_role</pre><h3>6. Tags: Selective Execution</h3><p><strong>Concept:</strong> <strong>Tags</strong> are attributes applied to specific tasks or roles that allow you to run a subset of a playbook. This is useful for debugging or when you only want to update a specific part of a configuration (e.g., updating a config file) without running the entire installation process.</p><p><strong>Sample Code:</strong></p><pre>tasks:<br>  - name: Copy Config File<br>    copy:<br>      src: config.conf<br>      dest: /etc/app/config.conf<br>    tags: [ &quot;configuration&quot; ]  # Tag assigned to this task<br><br>  - name: Install heavy software<br>    apt:<br>      name: heavy_software<br>    tags: [ &quot;installation&quot; ]<br></pre><p><em>Command to execute only the configuration task:</em></p><pre>ansible-playbook site.yml --tags &quot;configuration&quot;</pre><h3>Summary Checklist</h3><ol><li><strong>Inventory:</strong> Lists managed nodes and groups.</li><li><strong>Playbook:</strong> YAML file defining the desired state and tasks.</li><li><strong>Variables:</strong> Placeholders for dynamic values to increase reusability.</li><li><strong>Roles:</strong> Standardized directory structure for organizing complex playbooks.</li><li><strong>Master Playbook:</strong> Entry point that maps roles to inventory groups.</li><li><strong>Tags:</strong> Labels for executing specific parts of a playbook.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6463ee79a90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spring Security Internal Flow A Simple Guide]]></title>
            <link>https://medium.com/@rajithaubandara/understanding-spring-security-internal-flow-a-simple-guide-71d2f35cbf60?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d2f35cbf60</guid>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 03:20:39 GMT</pubDate>
            <atom:updated>2026-01-11T03:32:19.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Security is a powerful framework that handles authentication and authorization in Java applications. If you’ve ever wondered what happens behind the scenes when a user logs in, this guide will walk you through the internal flow step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SE-NCbuDRilMJWMnIjg9AA.png" /></figure><h3>The Authentication Journey</h3><p>Let’s follow the path of a login request through Spring Security’s architecture:</p><h3>Step 1: User Enters Credentials</h3><p>Everything starts when a user submits their credentials (typically username and password) through a login form. This triggers the Spring Security filter chain.</p><h3>Step 2: Authentication Filter Intercepts the Request</h3><p>The <strong>Authentication Filter</strong> is the first checkpoint. It intercepts the incoming request and extracts the credentials. This filter is responsible for capturing the authentication attempt and passing it forward for processing.</p><h3>Step 3: Creating an Authentication Token</h3><p>The filter creates an <strong>Authentication</strong> object (usually a UsernamePasswordAuthenticationToken) containing the user&#39;s credentials. At this point, the authentication object is not yet authenticated - it&#39;s just a container holding the credentials.</p><h3>Step 4: Authentication Manager Takes Control</h3><p>The <strong>Authentication Manager</strong> is the coordinator of the authentication process. It doesn’t do the actual authentication work itself, but delegates it to the appropriate <strong>Authentication Provider</strong>.</p><h3>Step 5: User Details Service Retrieval</h3><p>The <strong>Authentication Provider</strong> needs to verify the credentials, so it calls the <strong>User Details Service</strong> to load the user information from your data source (database, LDAP, in-memory, etc.). This service retrieves the stored user details including the username, password, and authorities (roles/permissions).</p><h3>Step 6: Password Verification</h3><p>Once the user details are retrieved, the <strong>Password Encoder</strong> compares the submitted password with the stored (typically encrypted) password. If they match, authentication proceeds; if not, an authentication exception is thrown.</p><h3>Step 7: Authentication Success</h3><p>If everything checks out, the Authentication Provider returns a fully authenticated Authentication object to the Authentication Manager, which then returns it to the Authentication Filter.</p><h3>Step 8: Security Context Updated</h3><p>The authenticated Authentication object is stored in the <strong>Security Context</strong>. This context is maintained throughout the user&#39;s session and can be accessed anywhere in your application to check who the current user is and what permissions they have.</p><h3>Step 9 &amp; 10: Response Flow</h3><p>Finally, the Authentication Filter sends the response back to the user, typically redirecting them to the originally requested page or a default success page.</p><h3>Key Components Explained</h3><p><strong>Authentication Filter</strong>: The gatekeeper that intercepts authentication requests</p><p><strong>Authentication Manager</strong>: The coordinator that manages authentication providers</p><p><strong>Authentication Provider</strong>: The component that performs the actual authentication logic</p><p><strong>User Details Service</strong>: The bridge to your user data storage</p><p><strong>Password Encoder</strong>: Handles password encryption and comparison</p><p><strong>Security Context</strong>: The holder of the current user’s authentication information</p><h3>Why This Matters</h3><p>Understanding this flow helps you:</p><ul><li>Debug authentication issues more effectively</li><li>Customize specific parts of the authentication process</li><li>Implement custom authentication providers when needed</li><li>Better secure your applications by understanding the security layers</li></ul><p>Spring Security’s architecture is designed to be flexible and extensible. Each component in this flow can be customized or replaced to meet your specific security requirements, making it a powerful choice for securing Spring applications.</p><p>Whether you’re building a simple web application or a complex enterprise system, knowing how Spring Security processes authentication requests gives you the foundation to implement robust security measures in your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d2f35cbf60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Database Migrations]]></title>
            <link>https://medium.com/@rajithaubandara/the-power-of-database-migrations-1a8beeeab5af?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a8beeeab5af</guid>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 07:59:14 GMT</pubDate>
            <atom:updated>2026-02-18T16:36:07.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qqx39pRSxi10d-maex0ETw.png" /></figure><blockquote>Don’t Let <strong>Automatic Schema Management (</strong>Hibernate , Entity Framework Core.. <strong>)</strong>Truncate Your Production Data</blockquote><p><strong>What we’ll discuss:</strong></p><ul><li><strong>The Hidden Danger:</strong> How automatic schema updates in Hibernate/JPA can destroy production data.</li><li><strong>The Solution:</strong> What Database Migration is and why it’s essential for data integrity.</li><li><strong>How it Works:</strong> A step-by-step overview of the migration process.</li><li><strong>Key Benefit:</strong> Why migrations prevent data loss where ORM tools fall short.</li></ul><p>Imagine this scenario Your Spring Boot application is humming along in the production environment, serving thousands of users. A new feature requires a minor tweak to your data model perhaps adding a new column or changing a data type. You make the change in your Java entities, deploy the application, and… all your precious production data vanishes. Panic sets in.</p><p>This nightmare scenario is a very real risk for many applications that rely on Object-Relational Mapping (ORM) tools like Hibernate and Spring Data JPA, especially when their schema update capabilities are left unchecked.</p><h3>The Hidden Danger Hibernate’s Default Behavior</h3><p>By default, when you configure Hibernate (via Spring Data JPA) to automatically update your database schema using,</p><pre>spring.jpa.hibernate.ddl-auto=update </pre><p>it <strong>tries to align your database schema with your Java entity definitions</strong>. While incredibly convenient in development environments for rapid prototyping, this convenience becomes a liability in production.</p><p>When Hibernate detects a data type change or a structural alteration that it doesn’t know how to gracefully handle, its default (and often destructive) behavior can be to drop and re-create tables or columns, or even worse, <strong>truncate existing data</strong>. If you have live customer information, order history, or any other critical business data, this can lead to severe and irreversible data loss.</p><h3>The Solution Database Migrations</h3><p>To avoid this catastrophic outcome, we embrace <strong>Database Migrations</strong>. At its core, database migration is a systematic approach to managing and versioning changes to your database schema in a controlled, safe, and repeatable manner. It ensures that schema updates are applied precisely, without compromising existing data.</p><p>Think of it like version control (similar to Git) but specifically tailored for your database schema. Each change to the database structure is defined in a script, typically a plain .sql file, and these scripts are executed in a specific order.</p><h3>How It Works A Lift &amp; Shift of Schema Changes</h3><p>The fundamental principle of database migration is to decouple schema updates from the application’s ORM layer. Instead of relying on Hibernate to infer and apply changes, you explicitly define them. Here’s a simplified breakdown</p><ul><li><strong>Define Changes in SQL Scripts:</strong> Instead of just changing your JPA entity, you write a .sql file that contains the exact SQL commands needed to modify your schema (e.g., ALTER TABLE ADD COLUMN, CREATE INDEX). Each script is typically versioned (e.g., V1__create_users_table.sql, V2__add_email_to_users.sql).</li><li><strong>Migration Tool Takes Over:</strong> Tools like <strong>Flyway</strong> or <strong>Liquibase</strong> are integrated into your application’s startup process.</li><li><strong>Pre-Application Execution:</strong> When your application starts, the migration tool first inspects a special metadata table in your database (e.g., flyway_schema_history). This table records which migration scripts have already been successfully applied.</li><li><strong>Execute New Scripts:</strong> The tool then identifies any new, unapplied migration scripts and executes them against your database <em>before</em> your Spring Boot application’s main logic (including Hibernate’s entity scanning) fully starts.</li><li><strong>Schema is Updated:</strong> Once all necessary SQL scripts have run successfully, your database schema is brought up to date. Only then does your Spring Boot application with its new JPA entities fully initialize, connecting to an already prepared and correct schema.</li></ul><h3>Key Benefit: Preventing Data Loss</h3><p>The most significant advantage of this approach is data integrity. Since you are directly dealing with explicit SQL commands within your .sql files, you have granular control over every schema change.</p><ul><li><strong>No Accidental Truncation:</strong> Unlike Hibernate’s update strategy, which might truncate data if it can&#39;t figure out a safe way to apply a schema change, your ALTER TABLE commands will explicitly modify the schema without affecting existing row data unless you specifically command them to.</li><li><strong>Controlled Evolution:</strong> You can implement complex schema evolutions, such as renaming columns while migrating data, splitting columns, or merging them, all within your controlled SQL scripts.</li><li><strong>Auditable Changes:</strong> Every schema change is recorded as a versioned script, providing a clear history and audit trail of your database’s evolution.</li></ul><p>In essence, database migrations provide the “lift &amp; shift” capability for schema changes you described, ensuring that your production data remains intact while your application evolves. It’s an indispensable practice for any serious application running in a production environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a8beeeab5af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microservices and ACID How We Keep Data Reliable Without Tight Coupling]]></title>
            <link>https://medium.com/@rajithaubandara/microservices-and-acid-how-we-keep-data-reliable-without-tight-coupling-fa1fb27e819d?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa1fb27e819d</guid>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Mon, 15 Dec 2025 08:18:47 GMT</pubDate>
            <atom:updated>2025-12-15T08:37:58.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PymdJXOhrDsBkmATQoJOmg.png" /></figure><p>In the world of monolithic architecture, we took ACID for granted. It was the safety net that kept our data sane. But as we move to distributed microservices, we often have to trade these strict guarantees for scalability.</p><h3>A Quick Refresher: What is ACID?</h3><p>Before diving into how we handle data without it, let’s define what ACID actually protects in a traditional database transaction:</p><ul><li><strong>Atomicity (All or Nothing):</strong> If a user places an order, three things might happen: create the order, charge the card, and reduce inventory. Atomicity ensures that if <em>any</em> one of these steps fails, the entire transaction is rolled back. You never end up with a charged card but no order.</li><li><strong>Consistency (Rules are Rules):</strong> The database ensures data meets all validation rules immediately. For example, you cannot insert an Order for a User ID that doesn’t exist (referential integrity). The database moves from one valid state to another.</li><li><strong>Isolation (No Peeking):</strong> If two users try to buy the last item simultaneously, Isolation ensures their transactions don’t interfere with each other. One must finish before the other effectively takes place.</li><li><strong>Durability (Written in Stone):</strong> Once the database confirms “Transaction Complete,” that data is saved permanently to disk, even if the server crashes a millisecond later.</li></ul><p>But then we moved to microservices.</p><p>Specifically, imagine an E-commerce system split into three distinct services:</p><ol><li><strong>Users Service</strong> (PostgreSQL)</li><li><strong>Products Service</strong> (MongoDB)</li><li><strong>Orders Service</strong> (PostgreSQL)</li></ol><p>Suddenly, the orders table in the Orders Service cannot have a FOREIGN KEY (user_id) REFERENCES users(id) constraint. The users table is effectively on a different planet (or at least a different server).</p><p>Here is how we handle data reliability and consistency without the safety net of tight database coupling.</p><h3>1. Why We Avoid Foreign Key Constraints Between Services</h3><p>The core tenet of microservices is <strong>autonomy</strong>. Each service must own its data and choose the database technology best suited for its workload.</p><p>If the Orders Service had a direct database link to the Users Service to enforce a foreign key:</p><ul><li><strong>Coupling:</strong> A schema change in Users could break Orders.</li><li><strong>Performance:</strong> Orders would need to lock rows in Users, creating massive contention.</li><li><strong>Availability:</strong> If Users database goes down for maintenance, you can&#39;t even query Orders efficiently.</li></ul><p>By removing cross-service FKs, we gain the ability to scale and deploy services independently. However, we lose the database’s guarantee that user_id: 55 actually exists.</p><h3>2. Application-Level Integrity Checks</h3><p>Without database constraints, the application layer must step up. We replace “hard” constraints with “soft” verifications.</p><h3>The “Trust but Verify” Approach</h3><p>When the Orders Service receives a request to create an order for User 55, it cannot simply insert the row.</p><ol><li><strong>Synchronous Verification (The Check):</strong> The Orders Service makes a lightweight API call (or gRPC request) to the Users Service: GET /users/55/exists.</li><li><strong>Referential Integrity via IDs:</strong> We store the user_id strictly as a reference (a simple string or integer).</li><li><strong>Handling “Ghosts”:</strong> What if User 55 deletes their account right after we check? We design the UI to handle “Unknown User” gracefully, or we listen for UserDeleted events to flag historical orders.</li></ol><p><strong>Code Snippet (Conceptual):</strong></p><pre># Orders Service<br>def create_order(user_id, product_ids):<br>    # 1. App-Level Integrity Check<br>    if not users_client.is_valid_user(user_id):<br>        raise InvalidUserException(f&quot;User {user_id} does not exist.&quot;)<br># 2. Proceed with internal logic<br>    order = order_repo.save(user_id, product_ids)<br>    return order</pre><h3>3. Event-Driven Consistency (The Saga Pattern)</h3><p>The hardest part is maintaining consistency across write operations. How do we ensure we don’t sell an out-of-stock item if Products and Orders are separate?</p><p>We can’t use a distributed transaction (Two-Phase Commit) because it’s too slow and brittle. Instead, we use <strong>Event-Driven Architecture</strong> and <strong>Sagas</strong>.</p><h3>The Flow:</h3><ol><li><strong>Order Service:</strong> Creates an order in PENDING state. Publishes an event: OrderCreated.</li></ol><p><strong>2. Inventory Service:</strong> Listens for OrderCreated. It attempts to reserve stock.</p><ul><li><em>Success:</em> Publishes StockReserved.</li><li><em>Fail:</em> Publishes StockReservationFailed.</li></ul><p><strong>3. Order Service:</strong> Listens to the response.</p><ul><li><em>If </em><em>StockReserved:</em> Updates order status to CONFIRMED.</li><li><em>If </em><em>StockReservationFailed:</em> Updates order status to REJECTED.</li></ul><p>This approach relies on <strong>Eventual Consistency</strong>. For a few milliseconds, the system state might be “in-between,” but it will eventually settle into a consistent state.</p><h3>Handling Failures (Compensating Transactions)</h3><p>In a monolith, ROLLBACK undoes changes. In microservices, we must write <strong>Compensating Transactions</strong>.</p><p>If we successfully charged the user’s credit card but then failed to reserve inventory, we can’t just “undo” the charge. We must trigger a new transaction: RefundUser.</p><h3>Conclusion</h3><p>Giving up ACID transactions and Foreign Keys feels risky at first. However, by moving integrity checks to the application level and adopting event-driven patterns like Sagas, we trade strict immediate consistency for massive scalability and resilience. The database no longer dictates our architecture; our business logic does.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa1fb27e819d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Config Server (Centralize Your Microservices Configuration)]]></title>
            <link>https://medium.com/@rajithaubandara/config-server-centralize-your-microservices-configuration-79030405753f?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/79030405753f</guid>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Fri, 05 Dec 2025 10:46:53 GMT</pubDate>
            <atom:updated>2025-12-05T10:46:53.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vvzSMgxWSJvK4yQEmQDvw.png" /></figure><p>In distributed systems, hardcoding configuration properties (like database URLs or feature flags) is a bad practice. When you have multiple services running in different environments (Dev, QA, Prod), you need a central place to manage these settings without rebuilding your code.</p><p>In this tutorial, we will set up a <strong>Spring Cloud Config Server</strong> linked to a <strong>Remote Git Repository</strong> (GitHub), and verify it with a Client Service that supports dynamic refreshing.</p><h3>The Workflow</h3><ol><li><strong>Create the Config Server Service:</strong> Build the Spring Boot application.</li><li><strong>Create the Remote Repository:</strong> Set up a GitHub repo and config files.</li><li><strong>Connect:</strong> Configure the Server to talk to the Remote Repo.</li><li><strong>Test:</strong> Verify the server serves configurations.</li><li><strong>Refresh:</strong> Use Spring Boot Actuator to update config without restarting.</li></ol><h3>Phase 1: Create the Config Server Service</h3><p>First, we create the application that will act as the manager.</p><h3>1. Generate the Project</h3><p>Go to <a href="https://start.spring.io/">start.spring.io</a> and create a project with these details (matching your environment):</p><ul><li><strong>Project:</strong> Maven</li><li><strong>Language:</strong> Java (Version 21)</li><li><strong>Spring Boot:</strong> 4.0.0</li><li><strong>Dependencies:</strong></li><li>Config Server</li><li>Spring Boot Actuator</li></ul><h3>2. Enable the Server</h3><p>Open ConfigServerApplication.java. We need to add annotations: for enable the config server features</p><pre>package com.Scalable.E_Commerce.Platform.config_server;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.cloud.config.server.EnableConfigServer;<br><br>@SpringBootApplication<br>@EnableConfigServer    // Enables Config Server functionality<br><br>public class ConfigServerApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(ConfigServerApplication.class, args);<br>    }<br>}</pre><h3>Phase 2: Create the Remote Repository</h3><p>Now we need a remote place to store the configuration files. The Config Server will pull from here.</p><ol><li><strong>Create a GitHub Repository:</strong></li></ol><ul><li>Go to GitHub and create a new repository (e.g., named configuration-server).</li><li>Copy the HTTPS URL (e.g., <a href="https://github.com/RajithaUBandara21/configuration-server.git).">https://github.com/RajithaUBandara21/configuration-server.git).</a></li></ul><p>2.Create Configuration Files:</p><p>3.The Config Server looks for files named after the service name. Let’s create a configuration file for a hypothetical client named payment-service.</p><p>4.Create a file named payment-service.properties inside the repo and add:</p><pre>user.role=Admin custom.message=Initial config from GitHub!</pre><ol><li>Commit and Push:</li><li>Commit this file to the main branch of your remote repository.</li></ol><h3>Phase 3: Connect Service to Repo</h3><p>Now we configure the Spring Boot app (from Phase 1) to point to the Git repo (from Phase 2).</p><p>Open src/main/resources/application.properties and add the following configuration:</p><pre>spring.application.name=CONFIG-SERVER<br>server.port=8888<br># Git Repository Configuration<br>spring.cloud.config.server.git.uri=[https://github.com/RajithaUBandara21/configuration-server](https://github.com/RajithaUBandara21/configuration-server)<br>spring.cloud.config.server.git.clone-on-start=true<br>spring.cloud.config.server.git.default-label=main</pre><ul><li><strong>git.uri</strong>: The URL to your remote GitHub repo.</li><li><strong>default-label</strong>: The branch to check (usually main or master).</li><li><strong>clone-on-start</strong>: Tells the server to pull the repo immediately when it starts up.</li></ul><h3>Phase 4: Test with a Client Application</h3><p>Instead of checking the JSON response manually, let’s create a real <strong>Client Application</strong> (the “Payment Service”) to fetch and display the configuration string using a Controller.</p><h3>1. Create the Client Service</h3><p>Generate a new Spring Boot project (separate from the server) with the following dependencies:</p><ul><li>Spring Web</li><li>Config Client</li><li>Spring Boot Actuator</li></ul><h3>2. Configure the Connection</h3><p>In the client’s src/main/resources/application.properties, configure it to talk to the Config Server:</p><pre>spring.application.name=payment-service<br>server.port=8080<br><br># Connect to the Config Server running on port 8888<br>spring.config.import=optional:configserver:http://localhost:8888<br>management.endpoints.web.exposure.include=refresh<br></pre><h3>3. Create the Test Controller</h3><p>Create a MessageController.java to inject the value from the remote property file. We add @RefreshScope now so it&#39;s ready for Phase 5.</p><pre>package com.example.paymentservice;<br><br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.cloud.context.config.annotation.RefreshScope;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RestController;<br>@RestController<br>@RefreshScope<br>public class MessageController {<br>    @Value(&quot;${custom.message}&quot;)<br>    private String message;<br>    @GetMapping(&quot;/message&quot;)<br>    public String getMessage() {<br>        return &quot;Message from Remote Repo: &quot; + message;<br>    }<br>}</pre><h3>4. Run and Verify</h3><ol><li>Start the <strong>Config Server</strong> (Port 8888).</li><li>Start the <strong>Payment Service Client</strong> (Port 8080).</li><li>Open your browser to: <a href="http://localhost:8080/message">http://localhost:8080/message</a></li></ol><p><strong>Expected Output:</strong></p><blockquote><em>Message from Remote Repo: Initial config from GitHub!</em></blockquote><h3>Phase 5: Refresh Config using Actuator</h3><p>In a real scenario, you have a Client App (like payment-service) consuming this config. If you update the file on GitHub, the client needs to know about it without restarting.</p><h3>1. The Client Setup (Quick Overview)</h3><p>Ensure your Client App (payment-service) has the Spring Boot Actuator dependency and the following properties:</p><pre># Client application.properties<br>spring.config.import=optional:configserver:http://localhost:8888<br>management.endpoints.web.exposure.include=refresh</pre><p>And in your Java code, the class using the variables must have @RefreshScope:</p><pre>@RestController<br>@RefreshScope<br>public class MessageController { ... }</pre><h3>2. The Refresh Process</h3><p>Now, let’s update the configuration dynamically.</p><p><strong>Modify GitHub:</strong> Edit payment-service.properties in your remote repo. Change the message:</p><pre>custom.message=Updated via Actuator Refresh!</pre><p><em>Commit and push the change.</em></p><p><strong>Trigger Refresh:</strong> The client application doesn’t know about the change yet. You must trigger the refresh endpoint on the <strong>Client</strong>.</p><p>Run this CURL command (or use Postman):</p><pre>POST http://localhost:8080/actuator/refresh</pre><p><strong>Verify:</strong> The Actuator will respond with the keys that changed (e.g., [&quot;custom.message&quot;]). If you check your client app now, it will reflect the new values from GitHub without having restarted the JVM.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79030405753f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inter Service Communication( RestTemplate, WebClient, and FeignClient)]]></title>
            <link>https://medium.com/@rajithaubandara/inter-service-communication-resttemplate-webclient-and-feignclient-21f99303e6c5?source=rss-cb143e93805f------2</link>
            <guid isPermaLink="false">https://medium.com/p/21f99303e6c5</guid>
            <dc:creator><![CDATA[Rajithaubandara]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 10:58:07 GMT</pubDate>
            <atom:updated>2025-12-03T10:58:07.237Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVE-om1Xh87qCq0UT6VpSA.png" /></figure><h3>Inter Service Communication in Spring Boot( RestTemplate, WebClient, and FeignClient)</h3><p>In a microservices architecture, services rarely exist in isolation. They need to share data and trigger actions across boundaries. For example, an <strong>Order Service</strong> often needs to query a <strong>Product Service</strong> to check inventory before confirming a purchase.</p><p>While production environments often use Service Discovery (like Eureka), there are many valid scenarios — such as local development, testing, or simple deployments — where you just want to call a service directly via its IP address or localhost.</p><p>In this guide, we will explore the three most popular ways to handle this <strong>direct communication</strong> in Spring Boot:</p><ol><li><strong>RestTemplate</strong> (The classic way)</li><li><strong>WebClient</strong> (The modern, reactive way)</li><li><strong>FeignClient</strong> (The declarative way)</li></ol><h3>The Scenario</h3><p>We have two services running locally:</p><ul><li><strong>Product Service</strong>: Runs on http://localhost:8081. It has an endpoint GET /products/{id}.</li><li><strong>Order Service</strong>: Runs on http://localhost:8080. It needs to call the Product Service.</li></ul><h3>1. RestTemplate</h3><p><strong>Status:</strong> Maintenance Mode (Legacy) <strong>Type:</strong> Synchronous (Blocking)</p><p>RestTemplate has been the standard for Spring applications for over a decade. It is simple, robust, and easy to debug. However, it blocks the thread while waiting for a response, which can impact performance under very heavy loads.</p><h3>Step 1: Setup</h3><p>Add the web starter to your pom.xml:</p><pre>&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;</pre><h3>Step 2: Configuration</h3><p>We create a simple bean in your Application configuration or Main class.</p><p>Java</p><pre>@Configuration<br>public class RestTemplateConfig {<br>    <br>    @Bean<br>    public RestTemplate restTemplate() {<br>        return new RestTemplate();<br>    }<br>}</pre><h3>Step 3: Usage</h3><p>We inject the RestTemplate and use the full URL.</p><pre>@Service<br>public class OrderService {<br>@Autowired<br>    private RestTemplate restTemplate;<br>    public ProductDTO getProduct(Long id) {<br>       <br>        String url = &quot;http://localhost:8081/products/&quot; + id;<br>        <br>        return restTemplate.getForObject(url, ProductDTO.class);<br>    }<br>}</pre><h3>2. WebClient</h3><p><strong>Status:</strong> Recommended (Modern) <strong>Type:</strong> Asynchronous &amp; Non-blocking</p><p>WebClient is the modern successor to RestTemplate. It is part of the Spring WebFlux module. It uses a non-blocking I/O model, meaning a single thread can handle multiple requests concurrently.</p><h3>Step 1: Setup</h3><p>Add the WebFlux starter</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h3>Step 2: Configuration</h3><p>We create a WebClient bean. We can optionally set a base URL here to keep our code cleaner.</p><pre>@Configuration<br>public class WebClientConfig {<br>@Bean<br>    public WebClient webClient() {<br>        // Pre-configuring the Base URL<br>        return WebClient.builder().build();<br>        <br>                <br>    }<br>}</pre><h3>Step 3: Usage</h3><p>Since the base URL is already set in the config, we only specify the URI path.</p><pre>@Service<br>public class OrderService {<br>@Autowired<br>    private WebClient webClient;<br>    public ProductDTO getProduct(Long productId) {<br>        return webClient<br>                .get()<br>                .uri(&quot;/products/&quot; + productId)<br>                .retrieve()<br>                .bodyToMono(ProductDTO.class)<br>                .block(); // .block() forces it to wait (Synchronous)<br>                          // Remove .block() to keep it Asynchronous<br>    }<br>}</pre><h3>3. FeignClient (Spring Cloud OpenFeign)</h3><p><strong>Status:</strong> Popular for Microservices <strong>Type:</strong> Declarative</p><p>Feign is a “declarative” HTTP client. This means you don’t write the implementation code yourself. You simply create an interface, and Spring generates the code for you at runtime. It keeps your business logic extremely clean.</p><h3>Step 1: Setup (pom.xml)</h3><p>Feign requires <strong>Spring Cloud</strong>. We must define the versions carefully using Dependency Management.</p><pre>&lt;properties&gt;<br>    &lt;java.version&gt;17&lt;/java.version&gt;<br>    &lt;spring-cloud.version&gt;2023.0.0&lt;/spring-cloud.version&gt; &lt;----<br>&lt;/properties&gt;<br><br>&lt;dependencies&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>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>        &lt;artifactId&gt;spring-cloud-starter-openfeign&lt;/artifactId&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;<br>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;2023.0.0&lt;/version&gt; &lt;-------<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><h3>Step 2: Configuration</h3><p>Enable Feign in your main application class using @EnableFeignClients.</p><pre>@SpringBootApplication<br>@EnableFeignClients<br>public class OrderApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.run(OrderApplication.class, args);<br>    }<br>}</pre><h3>Step 3: Create the Interface</h3><p>We use the url property in @FeignClient to point directly to the service.</p><pre>// name: Required for internal id<br>// url: Direct URL to the service (must include http://)<br>@FeignClient(name = &quot;product-service&quot;, url = &quot;http://localhost:8081&quot;)<br>public interface ProductClient {<br>@GetMapping(&quot;/products/{id}&quot;)<br>    ProductDTO getProduct(@PathVariable(&quot;id&quot;) Long id);<br>}</pre><h3>Step 4: Usage</h3><p>Inject the interface into your service. It looks just like calling a local method!</p><p>Java</p><pre>@Service<br>public class OrderService {<br>@Autowired<br>    private ProductClient productClient;<br>    public ProductDTO getProduct(Long productId) {<br>        return productClient.getProduct(productId);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21f99303e6c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>