<?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 Abhijit Mondal Abhi on Medium]]></title>
        <description><![CDATA[Stories by Abhijit Mondal Abhi on Medium]]></description>
        <link>https://medium.com/@abhi.m.abhijit?source=rss-234af7f44a78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*c8shw7PYa0mxUW18</url>
            <title>Stories by Abhijit Mondal Abhi on Medium</title>
            <link>https://medium.com/@abhi.m.abhijit?source=rss-234af7f44a78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 10:59:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhi.m.abhijit/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[Optimistic vs Pessimistic Locking: What I Wish I’d Understood Earlier]]></title>
            <link>https://medium.com/@abhi.m.abhijit/optimistic-vs-pessimistic-locking-what-i-wish-id-understood-earlier-deb2656f6c34?source=rss-234af7f44a78------2</link>
            <guid isPermaLink="false">https://medium.com/p/deb2656f6c34</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Abhijit Mondal Abhi]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 17:41:51 GMT</pubDate>
            <atom:updated>2026-10-25T17:41:51.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6Q52BzJDbjHc8h0t6sOVQ.jpeg" /></figure><p>Ask most backend engineers about optimistic vs pessimistic locking and you get a neat one-liner: “optimistic uses a version number, pessimistic locks the row.” I gave that answer myself. It’s correct, and it’s also the answer that gets you a follow-up question you can’t fully handle.</p><p>This post goes one level deeper. What does the database actually execute? What breaks? And how do you decide between the two in a system where money moves every millisecond?</p><p>Start with the bug both techniques exist to prevent: the <strong>lost update</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COdHE1vXGPMZZVwKqjTsNQ.png" /></figure><p>Two withdrawals totalling 80 happened, but the final balance is 50, not 20. Transaction 2 silently overwrote Transaction 1’s work, and nothing threw an error.</p><p>Note that I said <em>transactions</em>, not threads. These two might run on different JVMs behind a load balancer. That’s why synchronized can&#39;t save you here, and why the fix has to live in the database.</p><h3>Optimistic locking: detect the conflict at write time</h3><p>Optimistic locking takes <strong>no lock at all</strong> while you read and work. It bets that conflicts are rare, and it catches them at the moment of writing.</p><p>In JPA, you add one field:</p><pre>@Entity<br>public class Account {<br>    @Id<br>    private Long id;<br>    private BigDecimal balance;<br>    @Version<br>    private Long version;<br>}</pre><p>The interesting part is what Hibernate does on update. It doesn’t read the version again and compare. That would be a separate step, and another transaction could slip in between. Instead, the check is part of the write itself:</p><pre>UPDATE account<br>SET balance = 70, version = 6<br>WHERE id = 42 AND version = 5;</pre><p>If another transaction already bumped the version to 6, the WHERE clause matches nothing and <strong>0 rows are affected</strong>. Hibernate sees that and throws OptimisticLockException, which Spring wraps as ObjectOptimisticLockingFailureException. The check and the write are one atomic statement, so there is no gap.</p><p>Replay the lost-update table with @Version: Transaction 2&#39;s write now fails instead of silently winning.</p><p>Two details people often get wrong:</p><ul><li><strong>Retry is not automatic.</strong> The framework only throws. Your code decides whether to re-read the row, re-apply the business logic and try again, for example with Spring Retry’s @Retryable.</li><li><strong>A retry isn’t always safe.</strong> In trading, the price may have moved since the first attempt. Blindly retrying can execute at a price the user never agreed to.</li></ul><p><strong>The cost of optimistic locking is retries.</strong> With little contention, that cost is close to zero. With heavy contention, transactions keep failing and retrying, and you get a retry storm.</p><h3>Pessimistic locking: lock first, then work</h3><p>Pessimistic locking assumes a conflict <em>will</em> happen, so it locks the row before touching it. Other transactions that want the same row block until the lock is released at commit or rollback.</p><p>In Spring Data JPA:</p><pre>public interface AccountRepository extends JpaRepository&lt;Account, Long&gt; {<br>    @Lock(LockModeType.PESSIMISTIC_WRITE)<br>    @Query(&quot;select a from Account a where a.id = :id&quot;)<br>    Account findByIdForUpdate(@Param(&quot;id&quot;) Long id);<br>}</pre><p>This is the SQL it produces:</p><pre>SELECT * FROM account WHERE id = 42 FOR UPDATE;</pre><p>The lock is <strong>row-level</strong>, not table-level, and it lives as long as the transaction. (PESSIMISTIC_READ maps to a shared lock, FOR SHARE in PostgreSQL. It lets others read but not write.)</p><p>If you replay the lost-update table, Transaction 2 now waits at its read until Transaction 1 commits. It then reads 70, not 100, and writes 20. Correct.</p><p><strong>The cost of pessimistic locking is more than waiting.</strong> In production you also pay for:</p><ul><li><strong>Deadlocks</strong>, when two transactions lock rows in opposite orders (next section).</li><li><strong>Lock timeouts</strong>, when a transaction waits too long and fails anyway.</li><li><strong>Connection-pool exhaustion.</strong> Every blocked thread still holds a database connection. Enough waiters and the pool runs dry, and suddenly unrelated endpoints fail too.</li><li><strong>Long transactions hurt everyone.</strong> A slow external call made while holding a lock makes every other transaction queue behind it.</li></ul><h3>The deadlock trap: A→B and B→A at the same moment</h3><p>Here’s the follow-up question that separates a textbook answer from real experience: <em>a transfer locks both accounts pessimistically. Two transfers run at the same time, A→B and B→A. What happens?</em></p><p>If each transfer locks its “from” account first, you get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2kwS99oqaaSNhlpVAvusQ.png" /></figure><p>Each transaction holds the lock the other one needs. Neither can commit, so neither will ever release. That’s a <strong>deadlock</strong>.</p><p>The database won’t hang forever. PostgreSQL checks for deadlocks after deadlock_timeout (1 second by default). MySQL&#39;s InnoDB detects them immediately. Either way, the database picks a victim and rolls it back, and your Spring code sees an exception such as CannotAcquireLockException. Detection is a safety net, but you still lose a transaction. The real fix is to make the cycle impossible.</p><h4>An analogy: two keys, one rule</h4><p>Two colleagues each need both a red key and a blue key to open a safe. Anna grabs red first, Ben grabs blue first. Now Anna holds red and waits for blue, and Ben holds blue and waits for red. They wait forever.</p><p>Now add one rule: <strong>everyone takes the red key first.</strong> Ben goes for red, finds Anna has it, and waits while holding nothing. Anna takes blue, finishes, and returns both keys. Ben goes next. The worst case is a queue, never a cycle.</p><p>That rule is a <strong>global lock order</strong>.</p><h4>Global lock ordering in code</h4><p>For accounts, the natural order is the id: always lock the smaller id first.</p><pre>@Transactional<br>public void transfer(long fromId, long toId, BigDecimal amount) {<br>    // Phase 1: lock in GLOBAL order (ignores money direction)<br>    Account first  = repo.findByIdForUpdate(Math.min(fromId, toId));<br>    Account second = repo.findByIdForUpdate(Math.max(fromId, toId));<br>    // Phase 2: move money in BUSINESS direction<br>    Account from = first.getId().equals(fromId) ? first : second;<br>    Account to   = (from == first) ? second : first;<br>    from.debit(amount);<br>    to.credit(amount);<br>}</pre><p>The part that confused me at first: <strong>lock order and money direction are two separate decisions.</strong> For the B→A transfer, with A = id 1 and B = id 2, the transaction locks A first, but it still debits B.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHIHBjuB5eJxjqVUZPRJRg.png" /></figure><p>Once a transaction holds both locks, nobody else can touch either row, so it can move money in whichever direction the request says.</p><p>A few supporting measures complete the picture:</p><ul><li>Set a <strong>lock timeout</strong> (jakarta.persistence.lock.timeout) so a request fails fast instead of hanging.</li><li>Keep transactions <strong>short</strong>: no pricing calls or Kafka publishes while holding locks.</li><li><strong>Retry the deadlock victim.</strong> A deadlock is a transient failure, so a retry usually succeeds.</li></ul><h3>Choosing in a trading system: decide per row, not per domain</h3><p>My first instinct was “trading has lots of race conditions, so use pessimistic locking everywhere.” That’s too blunt. The deciding factor is <strong>contention on a specific row</strong>, not the business domain. One trading platform holds both kinds of data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFqvwYSmv6k6aMujhN6UCQ.png" /></figure><p>Two rows in that table deserve a closer look.</p><p><strong>The atomic conditional update.</strong> For a simple “reserve funds” step, you often don’t need an explicit lock at all:</p><pre>UPDATE account<br>SET balance = balance - 30<br>WHERE id = 42 AND balance &gt;= 30;</pre><p>The database applies the read, the check and the write as one statement. If it affects 0 rows, the account had insufficient funds. There’s no lock held across round trips, no version field and no retry loop. It’s often the fastest correct option for hot counters and balances.</p><p><strong>Designing contention away.</strong> High-throughput matching engines, such as the LMAX architecture, process each instrument on a single thread in memory. When only one thread ever touches the order book, there is nothing to lock. Sometimes the best locking strategy is a design where you don’t need one.</p><h3>Takeaways</h3><ul><li><strong>Optimistic</strong> = no lock; conflict detected at write time by WHERE version = ?. Costs retries, so it suits low contention.</li><li><strong>Pessimistic</strong> = SELECT … FOR UPDATE; others block until commit. Costs waiting, deadlocks, timeouts and pool connections, so it suits hot rows.</li><li><strong>Deadlocks</strong> come from locking in different orders. Prevent them with a global lock order, and keep lock order separate from business direction.</li><li><strong>Choose per row, not per domain.</strong> And check whether an atomic conditional update, or a design without shared state, removes the need for a lock entirely.</li></ul><p>Thanks for reading. If this helped, follow me for more deep dives into Java and Spring internals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deb2656f6c34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Resilient Microservices in Spring Boot: Retry, Circuit Breaker & Bulkhead Explained]]></title>
            <link>https://medium.com/@abhi.m.abhijit/building-resilient-microservices-in-spring-boot-retry-circuit-breaker-bulkhead-explained-8e8a5655a0bb?source=rss-234af7f44a78------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e8a5655a0bb</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Abhijit Mondal Abhi]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 19:15:39 GMT</pubDate>
            <atom:updated>2026-03-01T19:23:09.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern microservices don’t fail in obvious ways.</p><p>They fail slowly.<br>They fail partially.<br>They fail under load.<br>And sometimes, they fail in ways that break everything else.</p><p>In this article, I’ll walk through how I implemented <strong>Retry</strong>, <strong>Circuit Breaker</strong>, and <strong>Bulkhead</strong> in a Spring Boot microservice using <strong>Resilience4j</strong> — and more importantly, <em>why each one matters</em>.</p><p><strong>The Problem: Calling Another Service Is Dangerous</strong></p><p>Imagine:</p><ul><li>Service <strong>Berlin</strong> calls service <strong>Munich</strong></li><li>Munich becomes slow (6 seconds)</li><li>100 users hit Berlin at once</li></ul><p>What happens?</p><p>Without protection:</p><ul><li>Threads block</li><li>Retries multiply load</li><li>Failure cascades</li><li>The whole system degrades</li></ul><p>This is where resilience patterns come in.</p><p><strong>Step 1: Timeout — Always Fail Fast</strong></p><p>First rule of distributed systems:</p><blockquote>Never wait forever.</blockquote><pre>.timeout(Duration.ofSeconds(2))</pre><p>If Munich doesn’t respond in 2 seconds, Berlin fails fast.</p><p>Why this matters:</p><ul><li>Protects threads</li><li>Prevents infinite blocking</li><li>Keeps system responsive</li></ul><p>But timeout alone is not enough.</p><p><strong>Step 2: Retry — Handle Temporary Failures</strong></p><p>Sometimes failures are transient:</p><ul><li>Service just restarted</li><li>Short network glitch</li><li>Temporary overload</li></ul><p>Retry helps recover automatically.</p><p>Configuration</p><pre>resilience4j:<br>  retry:<br>    instances:<br>      munich:<br>        maxAttempts: 3<br>        waitDuration: 500ms<br>        enableExponentialBackoff: true<br>        exponentialBackoffMultiplier: 2<br>        retryExceptions:<br>          - org.springframework.web.client.ResourceAccessException<br>          - java.net.SocketTimeoutException</pre><h4>What this means</h4><ul><li>Try up to 3 times</li><li>Wait 500ms between attempts</li><li>Double the delay each time (500ms → 1000ms → 2000ms)</li><li>Retry only technical failures (not business errors)</li></ul><h3>Important Insight</h3><p>Never retry:</p><ul><li>400 Bad Request</li><li>404 Not Found</li><li>401 Unauthorized</li></ul><p>Retry only technical failures, not business failures.</p><p><strong>Step 3: Circuit Breaker — Stop Attacking a Dead Service</strong></p><p>Retry helps with temporary issues.</p><p>But what if Munich is completely down?</p><p>Retry would multiply traffic:</p><pre>100 users × 3 retries = 300 calls</pre><p>That’s dangerous.</p><p>Circuit breaker says:</p><blockquote>“If failure rate is too high, stop calling Munich for a while.”</blockquote><p>Configuration</p><pre>resilience4j:<br>  circuitbreaker:<br>    instances:<br>      munich:<br>        slidingWindowType: COUNT_BASED<br>        slidingWindowSize: 10<br>        minimumNumberOfCalls: 5<br>        failureRateThreshold: 50<br>        waitDurationInOpenState: 10s<br>        permittedNumberOfCallsInHalfOpenState: 3</pre><h4>How It Works</h4><ul><li>Look at last 10 calls</li><li>If at least 5 calls happened</li><li>And ≥ 50% failed → open circuit</li><li>Stay open for 10 seconds</li><li>Then test with 3 calls (half-open state)</li></ul><p><strong>Step 4: Bulkhead — Protect Your Threads</strong></p><p>Retry and Circuit Breaker protect logic.</p><p>Bulkhead protects resources.</p><p>Spring MVC uses one thread per request.</p><p>If Munich is slow and 100 users call Berlin:</p><ul><li>100 threads block</li><li>Thread pool exhausts</li><li>Entire service becomes unresponsive</li></ul><p>Bulkhead limits concurrency.</p><p>Configuration</p><pre>resilience4j:<br>  bulkhead:<br>    instances:<br>      munich:<br>        maxConcurrentCalls: 20<br>        maxWaitDuration: 0ms</pre><p>This means:</p><ul><li>Only 20 concurrent calls to Munich allowed</li><li>Others fail immediately</li><li>Berlin stays responsive</li></ul><p>This prevents thread pool exhaustion.</p><h4>Where Should These Annotations Live?</h4><p>They belong only at the <strong>external boundary</strong>:</p><pre>@Component<br>public class MunichClient {<br><br>    @Bulkhead(name = &quot;munich&quot;)<br>    @CircuitBreaker(name = &quot;munich&quot;)<br>    @Retry(name = &quot;munich&quot;)<br>    public List&lt;MunichCustomer&gt; getAllCustomers() {<br>        ...<br>    }<br>}</pre><h4>Final Thought</h4><p>Microservices fail. That’s normal.</p><p>Resilience is not about preventing failure.</p><p>It’s about:</p><ul><li>Containing failure</li><li>Isolating failure</li><li>Recovering from failure</li></ul><p>Retry only technical failures, not business failures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e8a5655a0bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradle vs Maven: Understanding the Real Difference (Especially the Lifecycle)]]></title>
            <link>https://medium.com/@abhi.m.abhijit/gradle-vs-maven-understanding-the-real-difference-especially-the-lifecycle-4d0338fa7788?source=rss-234af7f44a78------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d0338fa7788</guid>
            <dc:creator><![CDATA[Abhijit Mondal Abhi]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 00:22:32 GMT</pubDate>
            <atom:updated>2026-02-22T00:43:37.257Z</atom:updated>
            <content:encoded><![CDATA[<p>When developers switch between Maven and Gradle, the confusion usually starts with one word:</p><blockquote>“Lifecycle.”</blockquote><p>Both tools:</p><ul><li>Build Java projects</li><li>Manage dependencies</li><li>Compile, test, and package applications</li></ul><p>So what’s the real difference?</p><p>The answer isn’t syntax.<br>It’s <strong>architecture</strong>.</p><p>Let’s break it down properly.</p><h3>The Core Philosophical Difference</h3><p>Before discussing lifecycle, we must understand the fundamental distinction:</p><pre><br>| Maven                         | Gradle                     |<br>|-------------------------------|----------------------------|<br>| Phase-based build model       | Task-based build model     |<br>| Fixed lifecycle               | Dynamic task graph         |<br>| XML configuration             | Groovy / Kotlin DSL        |<br>| Convention over configuration | Highly customizable        |<br><br>This philosophical difference drives everything else.</pre><h3>Maven: Lifecycle-Driven Build</h3><p>Maven follows a <strong>predefined lifecycle</strong>.</p><p>When you run:</p><pre>mvn install</pre><p>Maven executes phases in order:</p><pre>validate → compile → test → package → verify → install → deploy</pre><p>Each phase automatically runs all previous phases. You don’t define this lifecycle. You don’t change it. It is fixed!</p><h3>Strength of Maven</h3><ul><li>Predictable structure</li><li>Standardized across teams</li><li>Easier onboarding</li><li>Strong convention</li></ul><h3>Limitation</h3><ul><li>Hard to customize lifecycle</li><li>Sequential execution</li><li>Less flexible</li></ul><h3><strong>Gradle: Task Graph Execution</strong></h3><p>Gradle works differently. When you run:</p><pre>./gradlew build</pre><p>Gradle does NOT follow fixed phases.</p><p>Instead:</p><ol><li>Plugins register tasks.</li><li>Tasks declare dependencies.</li><li>Gradle builds a <strong>Directed Acyclic Graph (DAG)</strong>.</li><li>Only required tasks are executed.</li></ol><p>Where Do Tasks Come From?</p><p>When you apply:</p><pre>plugins {<br>    id &#39;java&#39;<br>}</pre><p>The Java plugin automatically registers tasks like:</p><ul><li>compileJava</li><li>test</li><li>jar</li><li>assemble</li><li>check</li><li>build</li></ul><p>You didn’t define them. The plugin did!</p><h3>Lifecycle vs Task Graph</h3><p>Here is the real difference:</p><h3>Maven</h3><ul><li>Linear lifecycle</li><li>Fixed phase order</li><li>Always runs previous phases</li></ul><h3>Gradle</h3><ul><li>Task dependency graph</li><li>Flexible execution order</li><li>Runs only required tasks</li><li>Supports parallel execution</li><li>Supports incremental builds</li></ul><h3>Performance Comparison</h3><p><strong>Gradle</strong> generally performs better in large projects because:</p><ul><li>Incremental builds</li><li>Build caching</li><li>Parallel task execution</li><li>Configuration avoidance (tasks.register)</li></ul><p>Maven executes lifecycle phases sequentially.</p><h3><strong>Customization Power</strong></h3><p>In Maven, customization happens through plugins bound to phases.</p><p>In Gradle, you can define your own tasks:</p><pre>tasks.register(&quot;hello&quot;) {<br>    doLast {<br>        println(&quot;Hello, Gradle!&quot;)<br>    }<br>}</pre><p>You can attach tasks to existing ones:</p><pre>tasks.named(&quot;build&quot;) {<br>    dependsOn(&quot;hello&quot;)<br>}</pre><p>Gradle gives you full control over the build graph.</p><h3>When to Use What?</h3><h3>Maven is great when:</h3><ul><li>You want strict structure</li><li>You work in enterprise environments</li><li>You prefer convention over flexibility</li><li>You want minimal build scripting</li></ul><h3>Gradle is great when:</h3><ul><li>You need customization</li><li>You work with large microservice ecosystems</li><li>Build performance matters</li><li>You want modern DSL flexibility</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d0338fa7788" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying the Factory Pattern in Java Spring Boot: A Developer’s Guide]]></title>
            <link>https://medium.com/@abhi.m.abhijit/applying-the-factory-pattern-in-java-spring-boot-a-developers-guide-15c663a4db2c?source=rss-234af7f44a78------2</link>
            <guid isPermaLink="false">https://medium.com/p/15c663a4db2c</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Abhijit Mondal Abhi]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 18:35:34 GMT</pubDate>
            <atom:updated>2025-04-13T18:35:34.704Z</atom:updated>
            <content:encoded><![CDATA[<p>The Factory Pattern is a creational design pattern that provides a way to delegate the instantiation logic to subclasses or specific factory classes. It’s incredibly useful when you want to <strong>decouple object creation from its usage</strong>. In this blog post, I’ll walk you through how I applied this in a real-world Spring Boot application to build a dynamic <strong>Notification Service Factory</strong>.</p><p>While working on various projects — from small tools to large enterprise systems — I realized that I had been using the Singleton and Factory patterns unconsciously. So, I decided to dig deeper and document what I’ve learned. If you’ve also used these patterns without fully understanding them, this post is for you.</p><h3>🔧 The Problem</h3><p>Imagine you’re building an application that sends different types of notifications: <strong>Email</strong>, <strong>SMS</strong>, and <strong>Push</strong>. You want to switch between them dynamically based on a request or configuration.</p><p>Hardcoding logic like if (type.equals(&quot;email&quot;)) { ... } everywhere would:</p><ul><li>Break the Open/Closed Principle</li><li>Make testing harder</li><li>Lead to tightly coupled code</li></ul><p>The <strong>Factory Pattern</strong> can help.</p><h3>🎓 What Is the Factory Pattern?</h3><blockquote>The Factory Pattern is used to create objects <strong>without exposing the instantiation logic to the calling code</strong>. Instead of calling a constructor directly, you ask a factory for an instance based on a parameter (like a type or key).</blockquote><p>While it might seem like we’re specifying the class (because we use a type string like &quot;email&quot;), we are <strong>not</strong> creating the object ourselves — that responsibility lies with the factory. This way:</p><ul><li>The client doesn’t know or care which exact class is returned.</li><li>New implementations can be added without changing the client code.</li><li>The actual object creation is abstracted and centralized.</li></ul><p>In Spring, we can leverage <strong>dependency injection</strong> and <strong>interfaces</strong> to build a powerful and extensible factory.</p><h3>📚 Step-by-Step: Building a Notification Factory</h3><h3>1. Define an Interface</h3><pre>public interface NotificationService {<br>    void send(String message);<br>}</pre><h3>2. Implement Multiple Services</h3><pre>@Service<br>public class EmailNotificationService implements NotificationService {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending EMAIL: &quot; + message);<br>    }<br>}<br><br>@Service<br>public class SmsNotificationService implements NotificationService {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending SMS: &quot; + message);<br>    }<br>}<br><br>@Service<br>public class PushNotificationService implements NotificationService {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending PUSH: &quot; + message);<br>    }<br>}</pre><h3>3. Create the Factory</h3><pre>@Component<br>public class NotificationFactory {<br><br>    private final Map&lt;String, NotificationService&gt; services;<br><br>    public NotificationFactory(List&lt;NotificationService&gt; serviceList) {<br>        this.services = new HashMap&lt;&gt;();<br>        for (NotificationService service : serviceList) {<br>            String key = service.getClass().getSimpleName()<br>                .replace(&quot;NotificationService&quot;, &quot;&quot;)<br>                .toLowerCase();<br>            services.put(key, service);<br>        }<br>    }<br><br>    public NotificationService getService(String type) {<br>        NotificationService service = services.get(type.toLowerCase());<br>        if (service == null) {<br>            throw new IllegalArgumentException(&quot;Unsupported notification type: &quot; + type);<br>        }<br>        return service;<br>    }<br>}</pre><h3>🧱 Typical Factory with If-Else or Switch (Old Way)</h3><p>Before Spring and Dependency Injection, we often implemented Factory logic like this:</p><pre>public class SimpleNotificationFactory {<br><br>    public NotificationService getService(String type) {<br>        switch (type.toLowerCase()) {<br>            case &quot;email&quot;:<br>                return new EmailNotificationService();<br>            case &quot;sms&quot;:<br>                return new SmsNotificationService();<br>            case &quot;push&quot;:<br>                return new PushNotificationService();<br>            default:<br>                throw new IllegalArgumentException(&quot;Unsupported notification type: &quot; + type);<br>        }<br>    }<br>}</pre><h3>🚫 Why This Can Be a Problem:</h3><ul><li>You have to manage object creation manually</li><li>Violates Open/Closed Principle (modifying class to add new types)</li><li>Not test-friendly or scalable</li></ul><p>Spring’s DI-based factory is a modern, flexible improvement over this approach.</p><h3>📅 How It Works</h3><ul><li>Spring Boot injects <strong>all beans</strong> implementing NotificationService into the constructor.</li><li>The factory then maps those beans using a <strong>key</strong> (derived from class name).</li><li>You can retrieve the required implementation by calling getService(&quot;email&quot;), getService(&quot;sms&quot;), etc.</li></ul><h3>Benefits:</h3><ul><li>✅ Clean and dynamic service selection</li><li>✅ Open/Closed Principle compliance</li><li>✅ Easy to extend (just add a new @Service)</li><li>✅ Testable and maintainable</li></ul><h3>🚀 Usage in a REST Controller</h3><pre>@RestController<br>@RequestMapping(&quot;/notify&quot;)<br>public class NotificationController {<br><br>    private final NotificationFactory factory;<br><br>    public NotificationController(NotificationFactory factory) {<br>        this.factory = factory;<br>    }<br><br>    @PostMapping<br>    public ResponseEntity&lt;String&gt; send(@RequestParam String type, @RequestBody String message) {<br>        NotificationService service = factory.getService(type);<br>        service.send(message);<br>        return ResponseEntity.ok(&quot;Notification sent via &quot; + type);<br>    }<br>}</pre><h3>🧠 Conclusion</h3><p>This article is a result of my hands-on experience while building real-world projects. Over time, I realized I had been using the Factory Pattern and even Singleton without fully understanding their design rationale. Writing this post helped me solidify that understanding, and I hope it does the same for you.</p><p>The Factory Pattern — especially when paired with Spring Boot’s Dependency Injection — helps create clean, extensible, and maintainable code. Whether you’re working on notification services, payment gateways, or anything requiring flexible implementation switching, the Factory Pattern is your friend.</p><blockquote><em>“We often use design patterns unconsciously. But once we truly understand them, we use them wisely.”</em></blockquote><p>Have you used the Factory Pattern in your Spring Boot projects? I’d love to hear how and where you’ve applied it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15c663a4db2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Singleton Pattern in Java: A Developer’s Guide]]></title>
            <link>https://medium.com/@abhi.m.abhijit/singleton-pattern-in-java-a-developers-guide-51cb1539c25f?source=rss-234af7f44a78------2</link>
            <guid isPermaLink="false">https://medium.com/p/51cb1539c25f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <dc:creator><![CDATA[Abhijit Mondal Abhi]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 18:13:14 GMT</pubDate>
            <atom:updated>2025-04-05T18:15:05.079Z</atom:updated>
            <content:encoded><![CDATA[<p>Design patterns are proven solutions to common software design problems. One such pattern is the <strong>Singleton Pattern</strong> — a simple yet powerful technique to ensure a class has <strong>only one instance</strong> throughout the application lifecycle.</p><p>I’ve worked on a range of small to large-scale projects where sometimes I unknowingly used the Singleton pattern — without fully understanding how it works under the hood. This blog is both a personal note and a practical guide to finally grasp the <strong>why</strong>, <strong>when</strong>, and <strong>how</strong> of Singleton in Java.</p><p>Let’s dive into what it is, when to use it, and how to implement it effectively.</p><h3>🔎 What is the Singleton Pattern?</h3><p>The <strong>Singleton Pattern</strong> ensures that a class has only one instance and provides a global point of access to that instance.</p><h3>🌍 Real-world analogy:</h3><p>Think of a <strong>Printer Manager</strong> in an office. You don’t need one per employee. You just need <strong>one instance</strong> managing all print jobs.</p><h3>📊 When Should You Use Singleton?</h3><p>Singletons are useful when:</p><ul><li>You need <strong>a single point of coordination or control</strong> (like logging)</li><li>Managing shared resources like:<br>- Logging Service<br>- Configuration Manager<br>- Cache<br>- Database Connection Pool</li></ul><p>But be cautious: <strong>Singletons can lead to global state</strong>, which can make testing harder.</p><h3>⚖️ Basic Singleton Implementation in Java</h3><p>Here’s how you can create a simple Singleton class in Java:</p><pre>public class Logger {<br>    private static Logger instance;<br><br>    private Logger() {} // Step 1: Private constructor<br><br>    public static Logger getInstance() {<br>        if (instance == null) {<br>            instance = new Logger(); // Step 2: Create only if not already created<br>        }<br>        return instance; // Step 3: Return the same instance<br>    }<br><br>    public void log(String message) {<br>        System.out.println(&quot;[LOG] &quot; + message);<br>    }<br>}</pre><h3>🔧 Usage:</h3><pre>public class Main {<br>    public static void main(String[] args) {<br>        Logger logger1 = Logger.getInstance();<br>        Logger logger2 = Logger.getInstance();<br><br>        logger1.log(&quot;Application started&quot;);<br>        logger2.log(&quot;Another log&quot;);<br><br>        System.out.println(logger1 == logger2); // true<br>    }<br>}</pre><h3>🌪️ Making Singleton Thread-Safe</h3><p>In a multi-threaded application, the above approach could break. Here’s a thread-safe version using <strong>double-checked locking</strong>:</p><pre>public class Logger {<br>    private static volatile Logger instance;<br><br>    private Logger() {}<br><br>    public static Logger getInstance() {<br>        if (instance == null) { // First check<br>            synchronized (Logger.class) {<br>                if (instance == null) { // Second check<br>                    instance = new Logger();<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br>};</pre><h3>🧵 Why Do We Need Thread Safety?</h3><p>In a <strong>multi-threaded environment</strong>, multiple threads might try to create the Singleton instance <strong>at the same time</strong>. This can lead to multiple instances being created — which <strong>breaks the Singleton principle</strong>.</p><p>Java’s synchronized block along with volatile ensures:</p><ul><li>Only one thread can create the instance.</li><li>All threads see the most recent version of the instance.</li></ul><p>This is called <strong>double-checked locking</strong>, and it’s a popular way to safely create Singleton instances in concurrent environments.</p><h3>🔹 Enum Singleton (Simpler and Thread-Safe)</h3><p>The easiest and most efficient way to implement a Singleton in Java is by using an <strong>enum</strong>.</p><h3>💡 What is Enum Singleton?</h3><p>Java allows you to define <strong>enums with methods</strong>. When you define an enum with a single instance (like INSTANCE), Java guarantees that it:</p><ul><li>Is <strong>instantiated only once</strong></li><li>Is <strong>thread-safe</strong> by default</li><li>Handles <strong>serialization</strong> and <strong>reflection</strong> safely</li></ul><h3>✅ Example:</h3><pre>public enum LoggerSingleton {<br>    INSTANCE;<br><br>    public void log(String msg) {<br>        System.out.println(&quot;[LOG] &quot; + msg);<br>    }<br>}</pre><h3>🔧 Usage:</h3><pre>public class Main {<br>    public static void main(String[] args) {<br>        LoggerSingleton logger = LoggerSingleton.INSTANCE;<br>        logger.log(&quot;App started&quot;);<br>    }<br>}</pre><h3>📦 Why Use Enum Singleton?</h3><p>Unlike the traditional Singleton, using an enum offers several major advantages:</p><ul><li>✅ <strong>Thread-Safe by Default</strong><br> Java ensures that enum instances are created safely even in multithreaded contexts.</li><li>✅ <strong>Serialization Safe</strong><br> Enums handle serialization inherently — no need for custom readResolve() methods.</li><li>✅ <strong>Reflection Safe</strong><br> Reflection cannot create another instance of an enum. This avoids a common pitfall of classic Singletons.</li><li>✅ <strong>Minimal Boilerplate Code</strong><br> Enum Singletons require <strong>less code</strong>, making them easy to maintain and harder to get wrong.</li></ul><p>Java ensures that <strong>an enum’s constructor is only called once</strong>, and you can’t create another instance even using reflection or deserialization. That’s what makes it <strong>perfect for Singleton use cases</strong>.</p><h3>🚀 Spring Boot and Singleton</h3><p>In Spring Boot, all <strong>beans are Singleton by default</strong>:</p><pre>@Component<br>public class AppLogger {<br>    public void log(String msg) {<br>        System.out.println(&quot;[App] &quot; + msg);<br>    }<br>}</pre><p>You can inject AppLogger anywhere, and Spring will ensure the same instance is used.</p><h3>🌐 Summary</h3><ul><li>Singleton is ideal when <strong>one shared instance</strong> is enough.</li><li>Helps manage global/shared resources like <strong>loggers, configuration, or connections</strong>.</li><li>Be mindful of downsides like <strong>tight coupling</strong> or <strong>test difficulty</strong>.</li></ul><h3>🚫 When Not to Use Singleton</h3><ul><li>When you need <strong>multiple configurations</strong> or instances.</li><li>When testability and dependency injection are priorities.</li><li>Avoid it for <strong>business logic</strong> classes.</li></ul><h3>✍️ Final Thoughts</h3><p>The Singleton pattern is one of the easiest to understand but powerful when used correctly. Mastering it gives you a solid grasp of design thinking and prepares you to build more scalable, maintainable Java applications.</p><blockquote><em>“Use it wisely. Singleton is a tool, not a rule.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51cb1539c25f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement OpenAPI Generator in a Java SpringBoot application]]></title>
            <link>https://medium.com/@abhi.m.abhijit/how-to-implement-openapi-generator-in-a-java-spring-boot-application-9c2b942d9cce?source=rss-234af7f44a78------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c2b942d9cce</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[openapi-generator]]></category>
            <category><![CDATA[springboot-3]]></category>
            <dc:creator><![CDATA[Abhijit Mondal Abhi]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 09:29:12 GMT</pubDate>
            <atom:updated>2024-08-20T18:34:58.799Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>For the past few days, I’ve been working to integrate the most recent openAPI generator with the present Java SpringBoot application. All of the answers I’ve discovered are fairly obsolete. Later, I was able to combine with the most recent versions. Eventually, I detailed it here so that someone else may follow it easily.</blockquote><blockquote><strong>SpringBoot</strong>: 3.3.2<br><strong>openAPI Generator:</strong> 7.7.0<br><strong>openAPI specification:</strong> 3.1.0</blockquote><p>In this blog post, we’ll explore how to leverage the power of OpenAPI Generator in a Java Spring Boot application. OpenAPI Generator can be a game-changer in API development, offering tools to generate server stubs, client libraries, and API documentation automatically. Whether you’re starting a new project or integrating OpenAPI into an existing one, this guide will walk you through the entire process.</p><p>Table of Contents:</p><ol><li>Introduction to OpenAPI Generator</li><li>Why Use OpenAPI Generator?</li><li>Setting Up a Spring Boot Project</li><li>Integrating OpenAPI Generator</li><li>Generating Code from OpenAPI Specification</li><li>Implementing the Generated Interfaces</li><li>Modify application.yml or application.properties</li><li>Testing the Generated API</li><li>Conclusion</li><li><strong>Introduction to OpenAPI Generator</strong></li></ol><p>OpenAPI Generator is an open-source project that allows developers to generate client libraries, server stubs, API documentation, and configuration files from an OpenAPI Specification (formerly known as Swagger). It supports a wide range of programming languages and frameworks, making it a versatile tool for API development.</p><h4>What is OpenAPI?</h4><p>The OpenAPI Specification is a standard, language-agnostic interface description for REST APIs, allowing both humans and computers to discover and understand the capabilities of a service without accessing its source code. With OpenAPI, you can generate interactive API documentation, test your APIs, and even generate code.</p><p><strong>2. Why Use OpenAPI Generator?</strong></p><p>Implementing OpenAPI Generator in your Spring Boot project offers several advantages:</p><ul><li><strong>Automated Code Generation</strong>: Automatically generate boilerplate code, reducing manual coding effort and errors.</li><li><strong>Consistency</strong>: Ensure consistency across multiple client libraries and server implementations.</li><li><strong>Up-to-date documentation</strong>: Generate up-to-date, interactive API documentation with tools like Swagger UI.</li><li><strong>Easier Integration</strong>: Simplify the integration of your API with external systems by providing client SDKs in various languages.</li><li><strong>Automated Code Generation</strong>: Automatically generate boilerplate code, reducing manual coding effort and errors.</li><li><strong>Consistency</strong>: Ensure consistency across multiple client libraries and server implementations.</li><li><strong>Up-to-date documentation</strong>: Generate up-to-date, interactive API documentation with tools like Swagger UI.</li><li><strong>Easier Integration</strong>: Simplify the integration of your API with external systems by providing client SDKs in various languages.</li></ul><p><strong>3. Setting Up a Spring Boot Project</strong></p><p>First, let’s start by setting up a basic Spring Boot project. We’ll use Gradle for this tutorial.</p><p>You can create a new Spring Boot project using <a href="https://start.spring.io/">Spring Initializr</a> or directly from your IDE.</p><p>Dependencies to Include:</p><ul><li>Spring Web</li></ul><p>Here is my build.gradle configuration:</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.3.2&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.6&#39;<br>}<br><br>group = &#39;com.ama&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(21)<br>    }<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br>}<br><br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}</pre><p><strong>4. Integrating OpenAPI Generator</strong></p><p>Now that the basic project is set up, let’s integrate the OpenAPI Generator Gradle plugin.</p><p><strong>step 01:</strong> To integrate OpenAPI Generator, add the following plugin to your build.gradle:</p><pre>id &quot;org.openapi.generator&quot; version &quot;7.7.0&quot;</pre><p><strong>step 02:</strong> Now add the following dependencies:</p><pre>implementation &quot;org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0&quot;<br>implementation &#39;org.openapitools:jackson-databind-nullable:0.2.6&#39;</pre><p>step 03: Then add the following configuration:</p><pre>openApiGenerate {<br>    generatorName = &quot;spring&quot;<br>    inputSpec.set(file(&quot;${projectDir}/src/main/resources/static/openapi.json&quot;).toURI().toString())<br>    outputDir = &quot;$buildDir/generated&quot;<br>    apiPackage = &quot;com.ama.openapigenerator.api&quot;<br>    modelPackage = &quot;com.ama.openapigenerator.dto&quot;<br>    modelNameSuffix.set(&quot;Dto&quot;)<br>    groupId.set(&quot;com.ama.openapigenerator&quot;)<br>    configOptions = [<br>            library: &#39;spring-boot&#39;,<br>            dateLibrary: &#39;java8&#39;,<br>            interfaceOnly: &#39;true&#39;,<br>            skipDefaultInterface: &#39;true&#39;,<br>            useTags: &#39;true&#39;,<br>            useSpringBoot3: &#39;true&#39;,<br>    ]<br>}<br><br>sourceSets {<br>    main {<br>        java {<br>            srcDirs &quot;$buildDir/generated/src/main/java&quot;<br>        }<br>    }<br>}<br><br>compileJava.dependsOn tasks.openApiGenerate<br><br>openApiValidate {<br>    inputSpec.set(file(&quot;${projectDir}/src/main/resources/static/openapi.json&quot;).toURI().toString())<br>}</pre><blockquote><strong>Following is the complete build.gradle after adding all the configurations:</strong></blockquote><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.3.2&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.6&#39;<br>    id &quot;org.openapi.generator&quot; version &quot;7.7.0&quot;<br>}<br><br>group = &#39;com.ama&#39;<br>version = &#39;1.0.0&#39;<br><br>java {<br>    toolchain {<br>        languageVersion = JavaLanguageVersion.of(21)<br>    }<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &quot;org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0&quot;<br>    implementation &#39;org.openapitools:jackson-databind-nullable:0.2.6&#39;<br><br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>    testRuntimeOnly &#39;org.junit.platform:junit-platform-launcher&#39;<br>}<br><br>openApiGenerate {<br>    generatorName = &quot;spring&quot;<br>    inputSpec.set(file(&quot;${projectDir}/src/main/resources/static/openapi.json&quot;).toURI().toString())<br>    outputDir = &quot;$buildDir/generated&quot;<br>    apiPackage = &quot;com.ama.openapigenerator.api&quot;<br>    modelPackage = &quot;com.ama.openapigenerator.dto&quot;<br>    modelNameSuffix.set(&quot;Dto&quot;)<br>    groupId.set(&quot;com.ama.openapigenerator&quot;)<br>    configOptions = [<br>            library: &#39;spring-boot&#39;,<br>            dateLibrary: &#39;java8&#39;,<br>            interfaceOnly: &#39;true&#39;,<br>            skipDefaultInterface: &#39;true&#39;,<br>            useTags: &#39;true&#39;,<br>            useSpringBoot3: &#39;true&#39;,<br>    ]<br>}<br><br>sourceSets {<br>    main {<br>        java {<br>            srcDirs &quot;$buildDir/generated/src/main/java&quot;<br>        }<br>    }<br>}<br><br>compileJava.dependsOn tasks.openApiGenerate<br><br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}<br><br>openApiValidate {<br>    inputSpec.set(file(&quot;${projectDir}/src/main/resources/static/openapi.json&quot;).toURI().toString())<br>}</pre><p><strong>step 03:</strong> Prepare the OpenAPI Specification:</p><p>Place your OpenAPI specification file (openapi.json) in the src/main/resources/static directory. Here’s an example:</p><pre>{<br>  &quot;openapi&quot;: &quot;3.1.0&quot;,<br>  &quot;info&quot;: {<br>    &quot;title&quot;: &quot;Swagger Petstore - OpenAPI 3.1&quot;,<br>    &quot;version&quot;: &quot;1.0.11&quot;<br>  },<br>  &quot;paths&quot;: {<br>    &quot;/pet/{petId}&quot;: {<br>      &quot;get&quot;: {<br>        &quot;tags&quot;: [&quot;pet&quot;],<br>        &quot;summary&quot;: &quot;Find pet by ID&quot;,<br>        &quot;description&quot;: &quot;Returns a single pet&quot;,<br>        &quot;operationId&quot;: &quot;getPetById&quot;,<br>        &quot;parameters&quot;: [<br>          {<br>            &quot;name&quot;: &quot;petId&quot;,<br>            &quot;in&quot;: &quot;path&quot;,<br>            &quot;description&quot;: &quot;ID of pet to return&quot;,<br>            &quot;required&quot;: true,<br>            &quot;schema&quot;: {<br>              &quot;type&quot;: &quot;integer&quot;,<br>              &quot;format&quot;: &quot;int64&quot;<br>            }<br>          }<br>        ],<br>        &quot;responses&quot;: {<br>          &quot;200&quot;: {<br>            &quot;description&quot;: &quot;successful operation&quot;,<br>            &quot;content&quot;: {<br>              &quot;application/json&quot;: {<br>                &quot;schema&quot;: {<br>                  &quot;$ref&quot;: &quot;#/components/schemas/Pet&quot;<br>                }<br>              }<br>            }<br>          },<br>          &quot;400&quot;: {<br>            &quot;description&quot;: &quot;Invalid ID supplied&quot;<br>          },<br>          &quot;404&quot;: {<br>            &quot;description&quot;: &quot;Pet not found&quot;<br>          }<br>        },<br>        &quot;security&quot;: [<br>          {<br>            &quot;api_key&quot;: []<br>          },<br>          {<br>            &quot;petstore_auth&quot;: [&quot;write:pets&quot;, &quot;read:pets&quot;]<br>          }<br>        ]<br>      }<br>    }<br>  },<br>  &quot;components&quot;: {<br>    &quot;schemas&quot;: {<br>      &quot;Pet&quot;: {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>          &quot;id&quot;: {<br>            &quot;type&quot;: &quot;integer&quot;,<br>            &quot;format&quot;: &quot;int64&quot;<br>          },<br>          &quot;name&quot;: {<br>            &quot;type&quot;: &quot;string&quot;<br>          },<br>          &quot;status&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;description&quot;: &quot;pet status in the store&quot;,<br>            &quot;enum&quot;: [&quot;available&quot;, &quot;pending&quot;, &quot;sold&quot;]<br>          }<br>        }<br>      }<br>    },<br>    &quot;securitySchemes&quot;: {<br>      &quot;api_key&quot;: {<br>        &quot;type&quot;: &quot;apiKey&quot;,<br>        &quot;name&quot;: &quot;api_key&quot;,<br>        &quot;in&quot;: &quot;header&quot;<br>      },<br>      &quot;petstore_auth&quot;: {<br>        &quot;type&quot;: &quot;oauth2&quot;,<br>        &quot;flows&quot;: {<br>          &quot;implicit&quot;: {<br>            &quot;authorizationUrl&quot;: &quot;https://petstore3.swagger.io/oauth/authorize&quot;,<br>            &quot;scopes&quot;: {<br>              &quot;write:pets&quot;: &quot;modify pets in your account&quot;,<br>              &quot;read:pets&quot;: &quot;read your pets&quot;<br>            }<br>          }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p><strong>5. Generating Code from OpenAPI Specification</strong></p><p>Don’t forget to refresh the gradle after making any changes. Now, you should find <strong>openapi tools</strong> in gradle task menu in your IDE (in my case it was IntelliJ IDEA). Under that, you will find <strong>openApiGenerate</strong>. Just double-click <strong>openApiGenerate </strong>and you are good to go!</p><p>Or, you can use your command line interface and type:</p><pre> gradle clean openApiGenerate</pre><p>Now, you will find the generated interfaces and model classes under build &gt; generated &gt; src &gt; main.</p><p><strong>6. Implementing the Generated Interfaces</strong></p><p>Now the code is generated, it’s time to implement the generated interfaces.</p><p>The generated code will include an interface like PetApi. You need to implement this interface in a SpringBoot controller.</p><p>Following is my <strong>PetController</strong>, where I have implemented the <strong>PetApi</strong>.</p><pre>package com.ama.openapigenerator.controller;<br><br>import com.ama.openapigenerator.api.PetApi;<br>import com.ama.openapigenerator.dto.PetDto;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>public class PetController implements PetApi {<br><br>    @Override<br>    public ResponseEntity&lt;PetDto&gt; getPetById(Long petId) {<br>        return null;<br>    }<br>}</pre><p>Now run the application!</p><p><strong>7. Modify application.yml or application.properties</strong></p><p>To use updated openAPI (3.1.0), we need to configure our properties file. Just add the following setting:</p><pre>springdoc:<br>  api-docs:<br>    version: openapi_3_1</pre><p><strong>8. Testing the Generated API</strong></p><p>The springdoc-openapi-ui dependency automatically generates a Swagger UI for your API. Access it at <a href="http://localhost:8080/swagger-ui.html.">http://localhost:8080/swagger-ui/index.html</a></p><p><strong>9. Conclusion</strong></p><p>Integrating OpenAPI Generator with your Spring Boot project using Gradle offers a powerful way to streamline API development. By automating the generation of API interfaces, models, and client SDKs, you can significantly reduce boilerplate code, ensure consistency across your codebase, and effortlessly maintain up-to-date API documentation.</p><p>As you continue to work with OpenAPI and Gradle, don’t hesitate to explore further customizations and optimizations, ensuring that your API development process is as efficient and effective as possible.</p><p><strong>Source Code:</strong> <a href="https://github.com/abhijitmabhi/openapigenerator">https://github.com/abhijitmabhi/openapigenerator</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c2b942d9cce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install MongoDB shell in Windows]]></title>
            <link>https://medium.com/@abhi.m.abhijit/how-to-install-mongodb-shell-in-windows-1a79e6390fe8?source=rss-234af7f44a78------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a79e6390fe8</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[mongosh]]></category>
            <dc:creator><![CDATA[Abhijit Mondal Abhi]]></dc:creator>
            <pubDate>Tue, 30 May 2023 21:05:33 GMT</pubDate>
            <atom:updated>2023-05-30T21:05:33.436Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Prerequisite<br></strong>Must have a MongoDB deployment to connect</blockquote><p>Step 01:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJnvahq_EBdUGjYQUYrhvA.png" /></figure><p>Go to the following link to download MongoDB Shell</p><p><a href="https://www.mongodb.com/try/download/shell">MongoDB Shell Download</a></p><p>Step 02:</p><p>Unzip the downloaded file and copy the directory of the bin folder which is inside. For example:</p><pre>C:\mongosh-1.9.1-win32-x64\bin</pre><p>Step 03:</p><p>Now, add the above bin directory of windows Environment Variables.</p><p>Step 04:</p><p>Open cmd and type</p><pre>mongosh</pre><p>you should see your MongoDB Connection string.</p><p>step 05:</p><p>Now, it’s time for checking! Just type</p><pre>show dbs</pre><p>on the same cmd. You should see your available databases :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a79e6390fe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>