<?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 Kalpaj Patil on Medium]]></title>
        <description><![CDATA[Stories by Kalpaj Patil on Medium]]></description>
        <link>https://medium.com/@kalpajpatil07?source=rss-2cf7fe98c4c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bc1Bzb1CbOBM8dRol-3mrw.png</url>
            <title>Stories by Kalpaj Patil on Medium</title>
            <link>https://medium.com/@kalpajpatil07?source=rss-2cf7fe98c4c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 01:11:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kalpajpatil07/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[AWS Networking Essentials: Deploying a Minimal FastAPI App in the Cloud]]></title>
            <link>https://medium.com/@kalpajpatil07/aws-networking-essentials-deploying-a-minimal-fastapi-app-in-the-cloud-088800601807?source=rss-2cf7fe98c4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/088800601807</guid>
            <category><![CDATA[nat-gateway]]></category>
            <category><![CDATA[aws-vpc]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-networking]]></category>
            <dc:creator><![CDATA[Kalpaj Patil]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 11:31:10 GMT</pubDate>
            <atom:updated>2026-09-28T11:31:10.912Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>This is how I learned about regions, AZs, VPCs, subnets, route tables, NAT gateways, and load balancing</em></h4><p>AWS networking is overwhelming at first, until you start building and breaking things yourself. Over the weekend, I finally sat down to teach myself AWS networking, something that had been on my mind for a long time. And what better way to learn it than by deploying a small app myself? So let’s dive right in. Here’s what we’ll cover:</p><ul><li>Regions and availability zones (AZs)</li><li>VPCs and CIDR blocks</li><li>Public and private subnets</li><li>Route tables and the internet gateway</li><li>NAT gateways</li><li>Security groups</li><li>Load balancing</li></ul><p><strong>If you wish to follow along, you will need</strong></p><ul><li>An AWS account and access to the console</li><li>The <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a> installed on your computer</li></ul><blockquote>⚠️ <strong><em>A note on cost</em>: </strong>NAT gateways and load balancers aren’t part of the always-free services but if you have a new AWS account with free credits, those credits should cover this lab, so it’s essentially free.</blockquote><h4>Regions and availability zones (AZs)</h4><ul><li>A <strong>region</strong> is a geographic area, like Stockholm or Frankfurt. It’s <strong>not</strong> a single data center.</li><li>Each region contains several <strong>availability zones (AZs)</strong>, named like eu-north-1a and eu-north-1b. Each AZ is one or more separate data centers with its own power and networking.</li></ul><p>AZs are built so that a failure in one doesn’t take down the others. That’s why we’ll put a server in <strong>two</strong> AZs: if one goes down, the app keeps running.</p><p>Pick a region close to you and stay in it for the whole lab. Almost everything we create is tied to that region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*ZTk4IEhMv4OsMKujExB17A.png" /><figcaption>AWS region and VPC</figcaption></figure><h4>Step 1: Create the VPC</h4><p>A <strong>VPC</strong> (Virtual Private Cloud) is your own isolated network inside AWS. It lives in <strong>one region</strong> and spans <strong>all the AZs</strong> in it. Everything else in this guide (servers, load balancer, NAT gateway) lives inside it.</p><p>When you create a VPC, you give it a range of private IP addresses written as a <a href="https://aws.amazon.com/what-is/cidr/"><strong>CIDR block</strong></a>. So let’s take a quick detour.</p><p>An IP address like 10.11.0.0 is really 32 bits, in four groups of 8. A CIDR block like 10.11.0.0/16 means: <strong>the first 16 bits are fixed, and the rest can be anything.</strong></p><p>16 free bits give 2¹⁶ = <strong>65,536 addresses</strong>, from 10.11.0.0 to 10.11.255.255.</p><p>To split the 10.11.0.0/16 network into smaller subnets, we use a longer prefix, or a <strong>subnet mask</strong>. We will use <strong>/20</strong>, which can also be written as <strong>255.255.240.0</strong>. That&#39;s the size the VPC wizard uses by default, and <strong>/24</strong> is another common choice.</p><p>A /20 borrows 4 more bits from the third octet, so we get 2⁴ = <strong>16 subnets</strong>, each with 2¹² = <strong>4,096 addresses</strong>.</p><p><strong>Smallest subnet:</strong> all subnet bits(3rd octet) are 0 → 0000 0000 = <strong>0</strong> → 10.11.0.0/20</p><p><strong>Biggest subnet:</strong> all subnet bits(3rd octet) are 1 → 1111 0000 = 128 + 64 + 32 + 16 = <strong>240</strong> → 10.11.240.0/20</p><p>Start by creating your own VPC. I will be using the CIDR block discussed above: 10.11.0.0/16</p><p>You can name your VPC whatever you want. I am following the usual naming convention here: <strong>&lt;project&gt;-&lt;environment&gt;-&lt;resource&gt;</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QsLH5iZ9_lAQsRD_YH_pmw.png" /></figure><p>For this guide, we will use <strong>2 AZs with 2 public and 2 private subnets</strong>. For now, I haven’t configured a NAT gateway; we can do that later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZeXY1bhd9gpzFTH-XgRrw.png" /></figure><p>Click on Create VPC, and it will be ready for use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vixotdc3cf5Rj1x0zQzFOg.png" /></figure><p>We just created an isolated environment for ourselves.</p><h4>Subnets</h4><p>We created 4 subnets — 2 public and 2 private across 2 AZs in the VPC. But what does that mean? In the image below, you can see the network addresses under each subnet (they were assigned randomly with a subnet mask /20or 255.255.240.0)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwCsf9v3bofOyksmy6uhTA.png" /></figure><p>A <strong>subnet</strong> is a smaller slice of the VPC’s address range. The rules:</p><ul><li><strong>Each subnet lives in exactly one AZ.</strong> That’s why we need one per AZ.</li><li>One AZ can hold many subnets.</li><li>Subnets in the same VPC can’t overlap.</li><li><strong>AWS reserves 5 addresses in every subnet</strong> (the first four and the last one), so a /20 gives you 4,091 usable addresses, not 4,096</li></ul><p>The <strong>difference </strong>between a <strong>public and a private subnet</strong> will become clear once we look at route tables</p><h4>Route Tables</h4><p>A <strong>route table</strong> is attached to a subnet and decides <strong>where outgoing traffic goes next</strong>. Each row has:</p><ul><li>a <strong>destination</strong>: an IP range, inside or outside the VPC</li><li>a <strong>target</strong>: the next stop on the way to the destination, such as local, an internet gateway or a NAT gateway</li></ul><p>Look at the route table attached to the public subnet below.</p><ul><li>10.11.0.0/16 → local: anything addressed to the VPC stays inside the VPC. Every route table has this row, and you can&#39;t delete it.</li><li>0.0.0.0/0 → igw-...: everything else goes to the <strong>internet gateway</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwoeAkUis15XiXHNOOwaOg.png" /></figure><p>When a packet matches several rows, AWS picks the <strong>most specific</strong> one (the longest prefix). If traffic is headed to a resource with an IP like 10.11.x.x it belongs to our VPC&#39;s IP range 10.11.0.0/16, so the local row applies and the traffic never leaves the VPC. Any IP outside that range, such as Google&#39;s, only matches the 0.0.0.0/0 row, so it goes to the internet gateway</p><p>The <strong>internet gateway (IGW)</strong> is the VPC’s door to the internet. The wizard created one and attached it. It isn’t a server and has nothing to configure. It’s just the door that route tables point to.</p><h4>Public vs Private subnets</h4><p>Here’s the answer to “what makes a subnet public?”:</p><ul><li><strong>Public subnet:</strong> its route table has 0.0.0.0/0 → internet gateway</li><li><strong>Private subnet:</strong> it doesn’t</li></ul><p>That’s it. It’s all in the route table.</p><p>Check the route table on one of the private subnets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFVPbFjwKtVVG6gs2VSXHA.png" /></figure><p>There’s <strong>no Destination IP mapped to the internet gateway. </strong>So right now, instances in the private subnets <strong>can’t reach the internet at all</strong>.</p><p>Why would you want to make <strong>outbound calls to the internet</strong> from instances in private subnets anyway?</p><ul><li><strong>Installing software:</strong> pip install fastapi, or pulling Docker images all download packages from public servers.</li><li><strong>Security updates:</strong> the operating system needs to fetch patches regularly.</li><li><strong>Calling third-party APIs:</strong> real apps talk to outside services for payments (Stripe), email (SendGrid), maps, weather, AI models and more.</li></ul><p>To make <strong>outbound calls to the internet </strong>possible, there’s a technique — <strong>Network Address Translation,</strong> where a device <strong>rewrites the IP addresses in packets</strong> as they pass through it. Its main use is letting many devices with <strong>private IPs</strong> share <strong>one public IP</strong> to reach the internet.</p><h4>NAT (<strong>Network Address Translation</strong>) gateway</h4><p>You already use NAT every day: your home Wi-Fi router does it. Your laptop and phone have private IPs like192.168.1.x, but websites see only your router&#39;s single public IP. The router remembers which device made each request and sends the replies back to the right one.</p><p>It works by rewriting addresses. When a private server at 10.11.x.x calls an API:</p><ol><li>The packet leaves with <strong>source</strong> 10.11.x.x.</li><li>The private route table sends it to the NAT gateway.</li><li>The NAT gateway <strong>replaces the source</strong> with its own public IP and writes the connection down in a table.</li><li>The API replies to the NAT gateway’s public IP. It never sees the private address.</li><li>The NAT gateway looks up the reply in its table and forwards it back to 10.11.x.x.</li></ol><h4>Step 2: Create the NAT gateway</h4><p>Click on create NAT gateway. You will find NAT Gateways under VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74EXkIkqnCg6ycnowSIzlQ.png" /></figure><p>Give it a name and select the VPC created in the first step. Keep everything else set to the default configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECLIWeqWIFZTIn0B_Zcwhw.png" /></figure><p>Scroll down and click on Create NAT Gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhhFJU05agnpRyLxkexe3Q.png" /></figure><p>Now we must add a new route in our route tables linked to private subnets to map all outbound calls to the NAT gateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VjFE_f9BFMKYC19O_SpScA.png" /></figure><p>Click on Edit routes on the routes page.</p><p>Map 0.0.0.0/0 -&gt; NAT Gateway</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DO3dn_hw78BQeO_bWnRxTg.png" /></figure><p>Now we can make outbound calls from our app server instance inside the private subnet (in the VPC)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUidWHbPshtFs1c4zOLDCg.png" /></figure><h4>Step 3: Create an EC2 instance (This will be our FastAPI app server) in our VPC</h4><p>Give it a name and select Amazon Linux as our OS image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXt2UskhLwUyAEqqwE-eow.png" /></figure><p>We are not going to create a key pair for now, as we cannot ssh into our private instance directly as we won’t have a public IP for that.</p><p>Edit Network settings:</p><ol><li>select our VPC (fastapi-app-test-vpc)</li><li>select private-1 subnet (we will deploy the app here)</li><li>create a Security Group app-sg(no rules for now, we will add them later)</li></ol><p>Keep everything as default and click on Launch Instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myQL-uetwu0H2FDc-WXDiA.png" /></figure><p>Our EC2 instance is ready. As you can see there is not public IP attached to it. It is completely isolated in our VPC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wE_kreBYmwC2X8Y463iq-w.png" /></figure><p>To route traffic to our app server, we need a <strong>load balancer</strong>(exposed to the internet)</p><h4>Load Balancer</h4><p>In AWS, an <strong>Application Load Balancer (ALB)</strong> works with HTTP and HTTPS traffic. It sits in the <strong>public</strong> subnets, where users can reach it, and forwards each request to one of the servers in its <strong>target group</strong>, which stay safely in the <strong>private</strong> subnets.</p><h4>Step 4: Creating a target group and a load balancer</h4><p>Go to target groups and click on Create target group.</p><p>Give it a name fastapi-app-alb-target-groupand since our FastAPI app will expose port 8000, change the port from 80 to 8000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxiFF5BtcgJ_q5sR1OCWKw.png" /></figure><p>Scroll down, select our VPC and enter a health check endpoint</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zq9JKVwzzF5hfrvEUYokOw.png" /></figure><p>Keep everything else as default and click next</p><p>Select our EC2 instance and add port 8000 to include as pending</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GJfpUuEvAsjcTR5e5HbwQ.png" /></figure><p>Click Next, review the changes, and create the Target Group.</p><p>The health check shows unhealthy because we have not yet deployed our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ioclD-bv-VhZWpnJ4a9mA.png" /></figure><p>Go to Load Balancers and select Application Load Balancer (ALB).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Sj4sbb8iQ0nQ0g_18fEpQ.png" /></figure><p>Give it a name: fastapi-app-abl</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjxuJMQOWlKeDCbGjyznrg.png" /></figure><p>Select our VPC and both the AZs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5z0w5qdk7OH4OK539Dgbyg.png" /></figure><p>Leave the Security Group as default. We will configure all Security Groups later together.</p><p>Configure a <strong>target group</strong> (select the one we created earlier fastapi-app-alb-target-group)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1oteR6bk0Fhql2IoePfsQ.png" /></figure><p>Keep everything else as default, scroll down and create the load balancer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3HBpRA7b5bf_uyY3yCn1g.png" /></figure><h4>Step 4: Creating a security group for our ALB</h4><p>Give it a name alb-sg, description and select our VPC</p><p><strong>Inbound Rules: </strong>Allow all HTTP traffic on port 80</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ro2kF17qtGApr0bdB2LcbA.png" /></figure><p><strong>Outbound Rules: </strong>Route all HTTP traffic to our app server listening on port 8000 and our destination will be the security group attached to our app server app-sg</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXMmZGkbt2SaXE9S5JqDsA.png" /></figure><p>Attach the newly created alb-sg to our load balancer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V5RaL-l2j-7Nw273edTsVQ.png" /></figure><h4>Step 5: Modifying our app security group to accept incoming traffic from the load balancer security group</h4><p><strong>Inbound Rules: </strong>Allow all HTTP traffic on port 8000 from alb-sg</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87iWZcWSG4jIxbpkDnqxrQ.png" /></figure><p><strong>Outbound Rules: </strong>Keep it as 0.0.0.0/0 as the ALB will take of outgoing responses and the NAT gateway will take care of all outbound calls to the internet</p><p>We have configured everything we need for this guide (VPC, Route table, NAT, ALB and Security Groups for our App and ALB). Now we will deploy a FastAPI app to see the networking in action:</p><h3>Deploying the FastAPI app (via Session Manager)</h3><blockquote><strong><em>⚠️ Not for production.</em></strong><em> </em>We’re logging in to the server and setting up the app by hand to keep this guide focused on networking. Real deployments use a CI/CD pipeline, such as Docker images on ECS or pre-built AMIs in an Auto Scaling group, and nobody types commands on the servers. Session Manager is then kept for debugging.</blockquote><ol><li>Connect to the private server and switch to ec2-user:</li></ol><blockquote><strong><em>Note</em>:</strong> make sure the IAM role with the <strong>AmazonSSMManagedInstanceCore</strong> policy is attached to your instance (<strong>EC2 → Instances → your instance → Actions → Security → Modify IAM role</strong>). Without it, Session Manager can’t connect</blockquote><pre>aws ssm start-session --target &lt;your-instance-id&gt;<br>sudo su - ec2-user</pre><p>2.<strong> </strong>Set up the app (packages download through the NAT gateway):</p><blockquote><strong><em>Note</em>:</strong> make sure to install git, python and pip before you clone the repo</blockquote><pre>sudo yum install git python pip<br>git clone https://github.com/KalpajPatil/fastapi_for_aws.git<br>cd fastapi_for_aws<br>pip install -r requirements.txt<br>uvicorn app:app --host 0.0.0.0 --port 8000 --reload</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUv4_gU6MQ-wB8tTi707Vg.png" /></figure><p>3.<strong> </strong>Test the endpoints: Send a request from outside the VPC using an HTTP client like Postman to the load balancer public DNS which in my case is: <a href="http://fastapi-app-alb-289494770.eu-north-1.elb.amazonaws.com/">http://fastapi-app-alb-289494770.eu-north-1.elb.amazonaws.com/</a></p><p><strong>Test 1</strong>: GET <a href="http://fastapi-app-alb-289494770.eu-north-1.elb.amazonaws.com/health">http://fastapi-app-alb-289494770.eu-north-1.elb.amazonaws.com/health</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5S73jJLxlhxOwbnX2Cx9EQ.png" /></figure><p><strong>Test 2</strong>: GET <a href="http://fastapi-app-alb-289494770.eu-north-1.elb.amazonaws.com/api/users">http://fastapi-app-alb-289494770.eu-north-1.elb.amazonaws.com/api/users</a></p><blockquote>This endpoint makes an outbound call to the public API “https://jsonplaceholder.typicode.com/users” and thus uses a NAT gateway for communication</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kcj2WY6ZWodrvLVliLBtiw.png" /></figure><blockquote>Don’t forget to clean up your running resources!</blockquote><p>And that’s it. A small guide to setting up basic AWS networking by deploying a real app. You can find the code on my GitHub: [<a href="https://github.com/KalpajPatil/fastapi_for_aws">link</a>]. Thanks for reading! Happy networking :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=088800601807" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Magic behind Inversion of Control and Dependency Injection: @Configuration &…]]></title>
            <link>https://medium.com/@kalpajpatil07/understanding-the-magic-behind-inversion-of-control-and-dependency-injection-configuration-ad52f0ed2225?source=rss-2cf7fe98c4c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad52f0ed2225</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kalpaj Patil]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 15:21:48 GMT</pubDate>
            <atom:updated>2025-09-01T15:21:48.808Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the Magic behind Inversion of Control and Dependency Injection: @Configuration &amp; @Bean vs. @Component in Spring Boot</h3><p>If you’ve ever built an application with Spring Boot, you’ve probably marveled at how effortlessly everything seems to come together. You simply annotate a class with @Service or @Component, declare a dependency, and—<strong>poof</strong>—Spring handles all the wiring for you. It feels like magic, but what&#39;s actually happening behind the curtain?</p><p>This post isn’t just for developers new to Spring Boot but also for those Spring Boot users (like me LOL) who’ve been relying on this “magic” for years without fully understanding the core principles that make it all possible. This post is not simply a guide to walk you through the definitions of IoC and DI, but instead, it is a step-by-step walkthrough to uncover the use cases of the two primary methods of DI:</p><ol><li>The automatic, convention-based approach with @Component</li><li>The explicit, programmatic approach with @Configuration and @Bean</li></ol><p>For this post, let us take a practical example that can be related to a real-life use case. A backend developer trying to implement a payment processing feature in his e-commerce app is confused about whether to accept payments via PayPal. As of now, the only accepted payment is through a Razorpay gateway. Now, the developer has to figure out a way to include PayPal and also the possibility of adding or removing more payment gateways to the app.</p><p>Let us start coding and clear the concepts along the way.</p><p><strong>Method 1: </strong>Automatic convention-based approach with @Component first</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*3RcISL2x-8ZnmFUsG-ukDg.png" /><figcaption>controller class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*9QmefLUsC6k6KT8EsaCa6A.png" /><figcaption>request DTO</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*4014wQFx0r2WlIoNoO2ROA.png" /><figcaption>service class</figcaption></figure><p>You can already see DI in action in the above controller class. Our PaymentService is a service class annotated with @Service which is a special type of @Component . When the Spring IoC container finds a class annotated with @Component it knows that a bean of that class has to be injected wherever it is needed, in our case, in the controller constructor. This is called constructor injection. Other methods include setter injection and @Autowired annotation. Even the @Controller annotation is a special type of @Component . Now you may wonder…” Okay, so Spring decided to automatically inject a bean of the class with @Component annotation”. But how does Spring know what classes are annotated with @Component This is achieved by a process called a component scan which is performed by Spring on the specified package and it’s subpackage. But, we have not mentioned anywhere which package it is supposed to scan for components? Well, this happens because when the application is started, the @SpringBootApplication sitting on our main app secretly does it. How? Well, the @SpringBootApplication is actually a composite annotation made of @SpringBootConfiguration , @EnableAutoConfiguration and @ComponentScan .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*twbV6P8WKw-Bv8I1mfSUHw.png" /><figcaption>main app with @SpringBootApplication</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*wYaCyhXvPBshKOUlOCOG6w.png" /><figcaption>main app with @SpringBootConfiguration , @EnableAutoConfiguration and @ComponentScan</figcaption></figure><p>So the above 2 classes are exactly similar.</p><p>Well, now we know that Spring injects a bean(an instance) of a class annotated with @Component We can start creating our own component classes to inject them wherever required. Let’s start by creating a payment gateway interface so that we may implement them later as concrete classes and inject them as dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*q__kYa3n6BYAVv9PMrGcfQ.png" /><figcaption>PaymentGateway interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*fx0CUYtWaazM4XkZOA8e1g.png" /><figcaption>RazorPay concrete class</figcaption></figure><p>Our RazorPay implements the PaymentGateway interface, and it is annotated with @Component — hinting the Spring IoC Container to register itself as a bean and inject it wherever required. The bean will be identified with the id “razorpay” provided as a parameter to the @Component annotation. Now take a look at the service class again -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*4014wQFx0r2WlIoNoO2ROA.png" /><figcaption>service class</figcaption></figure><p>We have a Map&lt;String, PaymentGateway&gt; paymentGateways. Our concrete class implements the PaymentGateway interface, and so Spring will inject a bean of the RazorPay class into the PaymentService via constructor injection. The map key will be the bean id “razorpay” and the value will be the actual bean i.e., an instance of the RazorPay class. In this way, we can implement as many concrete classes of the PaymentGateway class and annotate them with @Component for Spring to inject them as beans. Now our backend developer can integrate as many gateways as needed. E.g.: A new concrete PayPal class is implemented. This time our bean id is “paypal” and the value will be the actual bean of the PayPal class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*MG1JrKxtxgwjjwayoEsPbw.png" /><figcaption>PayPal class</figcaption></figure><p>Well, this is all well and good, we are able to inject beans and decouple our object creation and usage. We are fulfilling the purpose of IoC in Spring. But there are a couple of drawbacks to this approach. Let&#39;s take a closer look at them</p><p>Drawback 1:</p><p>@Component always uses the default constructor to construct an instance of the class, i.e., Spring cannot inject a bean formed out of a parameterized constructor of the class.</p><p>Drawback 2:</p><p>We do not have any control over the beans. This is good and what IoC entails, but what about third-party service classes we want to inject into our own service classes? We cannot change the source code of these classes and simply add the @Component annotation to them.</p><p>Drawback 3:</p><p>Creating multiple bean instances and having control over them is very difficult</p><p>We can overcome these drawbacks by having more control over the bean creation process. This is where our second method comes into play</p><p><strong>Method 2:</strong> The explicit, programmatic approach with @Configuration and @Bean</p><p>By declaring our concrete classes as beans in a config class, which is annotated with the @Configuration annotation is how Spring container registers them as beans for injection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*1-pppz_7FZOClqAMvG88bw.png" /><figcaption>PaymentConfig class</figcaption></figure><p>Now Spring can inject the beans of RazorPay and PayPal classes into our PaymentService class. But there’s a catch here- we have modified our RazorPay class to include an api key. This tackles <strong>Drawback 1,</strong> we can now have beans created from parameterized constructors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*o8iJEgoYGPWAd6pzWhM__g.png" /><figcaption>modified RazorPay class</figcaption></figure><p><strong>Drawback 2</strong> can also be tackled with this method. For this demo example, since there is no third-party library required, I have included another example-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*65I0qLgQr0-_NgC82Nd51Q.png" /></figure><p>When storing password hashes in the database, we often use a BCryptPasswordEncoder to encrypt passwords. Though this is not a third-party library, it is a core Spring Framework class, and we cannot simply annotate the class with the @Component annotation.</p><p>With our explicit Bean creation method, tackling <strong>Drawback 3 </strong>is very convenient. Say you only want to enable RazorPay payments in Production and only disable the PayPal gateway, you can do something like-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*GnmYS7hfwvYb8D36y8Xliw.png" /></figure><p>The @ConditionalOnProperty now controls which bean should be injected depending on the value of the “payment.gateway” property set in our application.properties.</p><p>Although behind the scenes, Spring wires everything together on its own, it is interesting to know how Spring beans are being created and injected into our application. Really, the usage depends on our use case and the level of control we aim to achieve on the bean injection process. You will find the code snippets in this post in my GitHub repo: <a href="https://github.com/KalpajPatil/SpringBootIoC">https://github.com/KalpajPatil/SpringBootIoC</a></p><p>Thank you for taking your time to read this. Any feedback is welcome. Happy Learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad52f0ed2225" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>