<?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 Suparngautam on Medium]]></title>
        <description><![CDATA[Stories by Suparngautam on Medium]]></description>
        <link>https://medium.com/@suparngautam?source=rss-9ab5d1e79fb3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*q_kfYfEM61i03hCF</url>
            <title>Stories by Suparngautam on Medium</title>
            <link>https://medium.com/@suparngautam?source=rss-9ab5d1e79fb3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:28:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suparngautam/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[From Servlets to Spring MVC: Understanding What Really Happens Behind a Java Web Request]]></title>
            <link>https://medium.com/@suparngautam/from-servlets-to-spring-mvc-understanding-what-really-happens-behind-a-java-web-request-2508d77a7750?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2508d77a7750</guid>
            <category><![CDATA[servlets-to-spring-mvc]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 07:11:57 GMT</pubDate>
            <atom:updated>2026-07-05T07:11:57.087Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When I started learning Spring Boot, writing an API looked surprisingly simple.</p><p>@RestController<br>public class HelloController {</p><p>@GetMapping(“/hello”)<br> public String hello() {<br> return “Hello World”;<br> }<br>}</p><p>Just add @RestController, write a @GetMapping, start the application, and the API works.</p><p>But I had several questions:</p><p>• Who receives the HTTP request?<br>• How does Spring know which controller method to call?<br>• What is the role of Tomcat?<br>• What exactly does DispatcherServlet do?<br>• How is JSON converted into a Java object?<br>• Why do we need Controller, Service, and Repository layers?<br>• What is the difference between Spring MVC and Spring Boot?</p><p>To understand these questions properly, I started from the Servlet approach and then moved toward Spring MVC. This article explains that complete journey.</p><h3>The Big Picture</h3><p>A typical request in a Spring MVC application follows this flow:</p><p>Client → HTTP Request → Tomcat → DispatcherServlet → Controller → Service → Repository → Database</p><p>The response travels back through the same layers in reverse:</p><p>Database → Repository → Service → Controller → DispatcherServlet → Tomcat → HTTP Response → Client</p><p>This looks simple, but many things happen between these steps. To understand them, we first need to understand the problem with the traditional Servlet approach.</p><h3>Starting with the Servlet Approach</h3><p>Suppose we are creating an application with Users, Orders, and Payments. Using Servlets, we might create UserServlet, OrderServlet, and PaymentServlet.</p><p>@WebServlet(“/users”)<br>public class UserServlet extends HttpServlet {</p><p>@Override<br> protected void doGet(<br> HttpServletRequest request,<br> HttpServletResponse response<br> ) throws IOException {</p><p>// Read request parameters<br> // Validate input<br> // Call service<br> // Convert result to JSON<br> // Set response status<br> // Write HTTP response<br> // Handle exceptions<br> }<br>}</p><p>The same infrastructure code starts appearing repeatedly: request parameter extraction, request body reading, JSON conversion, validation, response creation, HTTP status codes, and exception handling.</p><p>But these are mostly HTTP and framework-level responsibilities. Our actual business logic might simply be: Create User, Find User, Calculate Order Total, Process Payment, or Cancel Order.</p><p>This raises an important design question: Why should every Servlet repeatedly handle the same HTTP infrastructure work?</p><p>This is one of the problems that a web framework such as Spring MVC helps solve.</p><h3>Enter Spring MVC</h3><p>Spring MVC is a web framework built around the Model–View–Controller architectural pattern. It can build REST APIs as well as server-rendered web applications using JSP or Thymeleaf.</p><p>For REST APIs, we commonly use annotations such as @RestController, @RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @RequestBody, @PathVariable, and @RequestParam.</p><p>@RestController<br>@RequestMapping(“/users”)<br>public class UserController {</p><p>@GetMapping<br> public List&lt;User&gt; getAllUsers() {<br> return userService.getAll();<br> }<br>}</p><p>Now consider GET /users. Who finds getAllUsers() and calls it? The answer begins with the DispatcherServlet.</p><h3>DispatcherServlet: The Heart of Spring MVC</h3><p>Spring MVC uses the Front Controller Pattern. Instead of directly mapping the entire application flow to separate Servlets, Spring MVC introduces a central entry point:</p><p>Request<br> ↓<br>DispatcherServlet<br> ↓<br>Correct Controller</p><p>DispatcherServlet is the central coordinator of the Spring MVC request-processing pipeline.</p><p>An important point is that Spring MVC does not remove the Servlet architecture. DispatcherServlet itself is a Servlet. Tomcat remains the Servlet container.</p><p>Client → Tomcat → DispatcherServlet → Spring MVC Infrastructure → Controller</p><h3>What Happens When a Request Arrives?</h3><p>Suppose the client sends GET /users/10. At a high level:</p><p>Client<br> ↓<br>Tomcat<br> ↓<br>DispatcherServlet<br> ↓<br>HandlerMapping<br> ↓<br>HandlerAdapter<br> ↓<br>UserController<br> ↓<br>UserService<br> ↓<br>UserRepository<br> ↓<br>Database</p><h3>Step 1: Tomcat Receives the Request</h3><p>Tomcat receives the HTTP request and provides the Servlet container environment. In a traditional Servlet, we directly work with HttpServletRequest and HttpServletResponse.</p><p>In Spring MVC, we usually work at a higher level:</p><p>@GetMapping(“/users/{id}”)<br>public User getUser(@PathVariable Integer id) {<br> return userService.getById(id);<br>}</p><p>Spring MVC handles much of the request-processing infrastructure around this method.</p><h3>Step 2: DispatcherServlet Receives the Request</h3><p>The request enters the Spring MVC processing pipeline through DispatcherServlet. It coordinates specialized Spring MVC components rather than personally performing every task.</p><p>HTTP Request<br> ↓<br>DispatcherServlet<br> ↓<br>HandlerMapping<br> ↓<br>HandlerAdapter<br> ↓<br>Controller<br> ↓<br>Service<br> ↓<br>Repository<br> ↓<br>Return Value Processing<br> ↓<br>HttpMessageConverter<br> ↓<br>HTTP Response</p><h3>Step 3: HandlerMapping Finds the Correct Controller</h3><p>Suppose StudentController has GET /students and POST /students methods. Both use the same path but different HTTP methods.</p><p>Spring needs to identify the correct handler using request information such as the URL path and HTTP method.</p><p>Conceptually:</p><p>GET /students → getAllStudents()<br>POST /students → createStudent()<br>GET /users/{id} → getUser()</p><p>HandlerMapping provides this mapping information and allows the framework to locate the correct handler.</p><h3>Step 4: HandlerAdapter Helps Invoke the Controller</h3><p>Finding the controller method is only one part of the job. Controller methods can have different parameters and annotations. One method may need a path variable, while another needs a Java object created from JSON.</p><p>HandlerAdapter, together with argument-resolution and data-binding infrastructure, helps invoke the selected controller method correctly.</p><p>HandlerMapping → Find the method<br>HandlerAdapter → Help invoke the method correctly</p><h3>Understanding @PathVariable, @RequestParam, and @RequestBody</h3><p>@PathVariable is used when a value is part of the URL path.</p><p>GET /users/10</p><p>@GetMapping(“/users/{id}”)<br>public User getUser(@PathVariable Integer id) {<br> return userService.getById(id);<br>}</p><p>@RequestParam is used for query-string values.</p><p>GET /users?id=10</p><p>@GetMapping(“/users”)<br>public User getUser(@RequestParam Integer id) {<br> return userService.getById(id);<br>}</p><p>@RequestBody is used when structured data is sent inside the HTTP request body, commonly as JSON.</p><p>@PostMapping(“/users”)<br>public User createUser(@RequestBody User user) {<br> return userService.create(user);<br>}</p><p>Example JSON:</p><p>{<br> “id”: 1,<br> “name”: “Aditya”<br>}</p><h3>JSON to Java Object Conversion</h3><p>Spring MVC uses message-conversion infrastructure to convert HTTP request and response bodies.</p><p>Incoming:<br>JSON Request Body → HttpMessageConverter → Java Object → Controller Method</p><p>Outgoing:<br>Controller Return Object → HttpMessageConverter → JSON → HTTP Response</p><p>In typical Spring Boot REST applications, Jackson is commonly used for JSON serialization and deserialization.</p><h3>The Role of the Spring IoC Container</h3><p>IoC means Inversion of Control. Instead of application code manually creating and wiring every dependency, Spring creates and manages objects called beans.</p><p>Spring IoC Container:<br>• UserController Bean<br>• UserService Bean<br>• UserRepository Bean</p><p>A common dependency chain is:</p><p>UserController → UserService → UserRepository → Database</p><p>Spring manages these components and injects their dependencies. This is why a controller does not need to manually create its service with new UserService().</p><h3>Why Controller, Service, and Repository?</h3><p>A common Spring application structure is:</p><p>Controller → Service → Repository → Database</p><p>The Controller handles the web-facing part of the application: receiving request-related input, delegating work, and returning the result.</p><p>The Service layer contains business logic and use-case coordination. Examples include checking whether an order can be cancelled, calculating discounts, verifying account status, applying payment rules, and coordinating multiple repository operations.</p><p>The Repository layer handles data access and abstracts persistence operations such as finding, saving, updating, and deleting data.</p><h3>Complete Example: GET Request Flow</h3><p>Suppose the client sends GET /users/10.</p><p>1. Client sends GET /users/10.<br>2. Tomcat receives the HTTP request.<br>3. The request enters DispatcherServlet.<br>4. HandlerMapping identifies the correct handler.<br>5. Spring resolves the path variable.<br>6. The value “10” is converted to Integer.<br>7. The controller method is invoked.<br>8. The controller calls UserService.<br>9. UserService executes business logic.<br>10. UserService calls UserRepository.<br>11. The repository accesses the database.<br>12. Data returns through Repository → Service → Controller.<br>13. Spring processes the controller return value.<br>14. The Java object is converted to JSON.<br>15. The HTTP response is sent to the client.</p><h3>Complete Example: POST Request Flow</h3><p>Suppose the client sends POST /users with a JSON request body.</p><p>Client sends JSON<br> ↓<br>Tomcat<br> ↓<br>DispatcherServlet<br> ↓<br>HandlerMapping finds createUser()<br> ↓<br>JSON → Java Object<br> ↓<br>Controller<br> ↓<br>Service<br> ↓<br>Repository<br> ↓<br>Database</p><p>The response returns as:</p><p>Saved User Object → Controller → Message Conversion → JSON → HTTP Response → Client</p><h3>Traditional Spring MVC and External Tomcat</h3><p>In a traditional Spring MVC deployment, an application may be packaged as a WAR file and deployed to an externally installed Tomcat server.</p><p>Spring MVC Application → Build WAR File → Install and Configure Tomcat → Deploy WAR → Start Tomcat</p><p>Tomcat is the Servlet container. Spring MVC is the web framework. Your application contains controllers, services, repositories, and business logic.</p><h3>What Spring Boot Changes</h3><p>Spring MVC and Spring Boot are not the same thing.</p><p>Spring MVC is the web framework. Spring Boot makes Spring applications easier to configure, package, and run.</p><p>A common Spring Boot web application contains:</p><p>• Application Code<br>• Spring MVC<br>• Auto-Configuration<br>• Embedded Tomcat</p><p>A common Spring Boot application can be started using:</p><p>mvn spring-boot:run</p><p>or:</p><p>java -jar application.jar</p><p>The embedded server starts with the application. This is one of the major conveniences Spring Boot provides.</p><h3>Servlet vs Spring MVC vs Spring Boot</h3><p>Servlet is the lower-level web API where developers often work directly with request and response objects.</p><p>Spring MVC is a web framework that provides the DispatcherServlet pipeline, annotation-based mappings, argument resolution, message conversion, and other web infrastructure.</p><p>Spring Boot simplifies application setup through auto-configuration and commonly uses an embedded server. It does not replace Spring MVC; it configures and runs Spring applications more conveniently.</p><h3>My Learning Progression</h3><p>The most useful part of learning this architecture was understanding each layer in order:</p><p>Core Java Networking<br> ↓<br>HTTP<br> ↓<br>Servlets<br> ↓<br>Tomcat<br> ↓<br>Spring MVC<br> ↓<br>Spring Boot</p><p>When we directly start with Spring Boot, a small @GetMapping endpoint can feel like magic. After understanding the underlying layers, the same code tells a much bigger story.</p><h3>Final Thoughts</h3><p>The biggest lesson for me was that Spring Boot does not perform magic. It provides abstractions and automation over concepts that already exist.</p><p>Tomcat still provides the Servlet container environment. DispatcherServlet acts as the central entry point for the Spring MVC request-processing pipeline. Handler mappings help identify the correct controller handler. The framework resolves controller arguments. Message converters handle transformations such as JSON to Java objects and Java objects back to JSON.</p><p>Controllers handle web-facing application flow. Services contain business logic. Repositories handle persistence.</p><p>Once this request lifecycle becomes clear, annotations such as @GetMapping, @PostMapping, @RequestBody, @PathVariable, and @RequestParam stop looking like isolated Spring features. They become parts of one complete request-processing architecture.</p><p>Client → Tomcat → DispatcherServlet → Controller → Service → Repository → Database</p><p>Sometimes the best way to understand a framework is not to start with what it makes easy, but with the problems it was designed to solve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2508d77a7750" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Core Java to Servlets, Tomcat, and Spring MVC]]></title>
            <link>https://medium.com/@suparngautam/from-core-java-to-servlets-tomcat-and-spring-mvc-be95856802c8?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/be95856802c8</guid>
            <category><![CDATA[java-to-servlets]]></category>
            <category><![CDATA[tomcat-and-spring-mvc]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 19:11:23 GMT</pubDate>
            <atom:updated>2026-07-04T19:11:23.015Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding what actually happens behind a Java web application</em></p><p>A practical journey from sockets and HTTP to a Servlet CRUD API, WAR deployment, DispatcherServlet, and embedded Tomcat.</p><p>When we start learning Spring Boot, creating an API feels almost too simple. We add an annotation, write a controller method, run the application, and send a request from Postman.</p><p>@GetMapping(“/users”)<br>public List&lt;User&gt; getUsers() {<br> return userService.getAll();<br>}</p><p>But behind this small method, a complete web stack is working. Something listens on port 8080. Something accepts the network connection, parses HTTP, creates request and response objects, finds the correct Java code, executes it, and sends a response back to the client.</p><p>I wanted to understand that complete journey before going deeper into Spring Boot. So I built a small User CRUD API using Java Servlets, Maven, Tomcat, and an in-memory HashMap. This article explains the concepts through that project.</p><p>The journey is: Core Java → Sockets → HTTP → Servlet API → Tomcat → WAR Deployment → Spring MVC → DispatcherServlet → Spring Boot.</p><h3>1. Everything Starts with Client–Server Communication</h3><p>Every web application begins with a client communicating with a server. The client may be a browser, Postman, a mobile application, a frontend application, or another backend service.</p><p>Client Server</p><p>— — — — HTTP Request — — — -&gt;<br> ← — — — HTTP Response — — — —</p><p>For example, a client may send:</p><p>GET /users HTTP/1.1<br>Host: localhost:8080</p><p>The server processes the request and returns an HTTP response:</p><p>HTTP/1.1 200 OK<br>Content-Type: application/json</p><p>[<br> {<br> “id”: 1,<br> “name”: “Gautam”,<br> “email”: “gautam@example.com”,<br> “mobile”: “9999999999”<br> }<br>]</p><p>At the highest level, every backend follows the same model: Request → Processing → Response. Frameworks change how we write the processing logic, but they do not change this fundamental model.</p><h3>2. What Is Inside an HTTP Request?</h3><p>An HTTP request contains a method, a target URL, headers, optional query parameters, and sometimes a request body. The method describes the operation the client wants to perform.</p><p>GET → Read data<br>POST → Create data<br>PUT → Replace or update data<br>PATCH → Partially update data<br>DELETE → Delete data</p><p>A server must accept the connection, parse the request, identify the method and path, read headers and parameters, execute application logic, create a valid HTTP response, and return it to the client. This raises an important question: can we do all of this with Core Java?</p><h3>3. Building a Server with Core Java</h3><p>Yes. Java provides low-level networking classes such as ServerSocket and Socket. A simplified server can begin like this:</p><p>ServerSocket serverSocket = new ServerSocket(8080);</p><p>while (true) {<br> Socket socket = serverSocket.accept();</p><p>// Read HTTP request<br> // Parse method, URL, headers, and body<br> // Execute application logic<br> // Build HTTP response<br> // Send response to client<br>}</p><p>Technically, we could build an entire HTTP server this way. The problem is the amount of infrastructure work involved. We would need to parse HTTP correctly, route URLs, manage connections and threads, handle concurrent clients, generate status lines and headers, deal with errors, and manage the lifecycle of application components.</p><p>If our actual goal is to build a User CRUD application, most of that work is unrelated to the business problem. This is where the Servlet API and Servlet Containers become useful.</p><h3>4. What Is a Servlet?</h3><p>A Servlet is a Java component designed to handle requests and produce responses inside a Servlet Container. A basic Servlet can look like this:</p><p>@WebServlet(“/hello”)<br>public class HelloServlet extends HttpServlet {</p><p>@Override<br> protected void doGet(<br> HttpServletRequest request,<br> HttpServletResponse response<br> ) throws IOException {</p><p>response.setContentType(“text/plain”);<br> response.getWriter().write(“Hello from Servlet”);<br> }<br>}</p><p>The @WebServlet(“/hello”) mapping tells the container that requests matching /hello should be handled by this Servlet. Instead of reading raw bytes from a socket, our code receives HttpServletRequest and HttpServletResponse objects.</p><p>String id = request.getParameter(“id”);<br>String token = request.getHeader(“Authorization”);<br>response.getWriter().write(“Hello”);</p><p>The Servlet API gives Java developers a standard programming model for HTTP. But a Servlet does not listen on a port or create itself. A runtime is still needed to receive requests, create and manage Servlet instances, dispatch HTTP methods, manage threads, and return responses. That runtime is the Servlet Container.</p><h3>5. What Is Tomcat?</h3><p>Apache Tomcat is a web server and Servlet Container commonly used to run Java web applications. In a Servlet application, Tomcat sits between the client and application code.</p><p>Browser / Postman<br> |<br> | HTTP Request<br> v<br> Tomcat<br> |<br> + — /hello → HelloServlet<br> + — /users → UserServlet<br> + — /orders → OrderServlet<br> + — /payments → PaymentServlet</p><p>Tomcat listens for connections, parses HTTP requests, creates HttpServletRequest and HttpServletResponse objects, finds the matching Servlet, invokes the appropriate request-processing flow, manages Servlet lifecycle and request threads, and sends the final HTTP response.</p><p>A useful separation of responsibility is this: application code decides what should happen for /users; Tomcat handles how the HTTP request reaches that code.</p><h3>6. The CRUD Project Architecture</h3><p>To make the concepts practical, I created a small User CRUD application. The project contains a model, a service, and a Servlet.</p><p>com.gautam<br>├── model<br>│ └── User.java<br>├── service<br>│ └── UserService.java<br>└── servlet<br> └── UserServlet.java</p><p>The runtime flow is:</p><p>Client<br> ↓<br>Tomcat<br> ↓<br>UserServlet<br> ↓<br>UserService<br> ↓<br>HashMap&lt;Integer, User&gt;</p><p>The HashMap is used only as a simple in-memory store so that the project stays focused on Servlets and Tomcat.</p><h3>7. The User Service Layer</h3><p>The service class contains the CRUD operations. It is independent of HTTP-specific objects, which is an important design idea: the Servlet handles HTTP concerns while the service handles application operations.</p><p>package com.gautam.service;</p><p>import com.gautam.model.User;</p><p>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;</p><p>public class UserService {</p><p>private Map&lt;Integer, User&gt; usersDb;</p><p>public UserService() {<br> usersDb = new HashMap&lt;&gt;();<br> }</p><p>public User createUser(User userReq) {<br> usersDb.put(userReq.getId(), userReq);<br> return userReq;<br> }</p><p>public List&lt;User&gt; getAll() {<br> return usersDb.values().stream().toList();<br> }</p><p>public User getUserById(Integer id) {<br> return usersDb.getOrDefault(id, null);<br> }</p><p>public Boolean deleteRecord(Integer id) {<br> User user = usersDb.getOrDefault(id, null);</p><p>if (user == null) {<br> return false;<br> }</p><p>usersDb.remove(user.getId());<br> return true;<br> }</p><p>public User updateUser(User userToBeUpdated) {<br> if (usersDb.containsKey(userToBeUpdated.getId())) {<br> usersDb.put(userToBeUpdated.getId(), userToBeUpdated);<br> return userToBeUpdated;<br> }</p><p>return null;<br> }<br>}</p><p>The same separation continues in larger applications: Controller or Servlet → Service → Repository → Database.</p><h3>8. Mapping the User Servlet</h3><p>The Servlet is mapped to /users and extends HttpServlet.</p><p>@WebServlet(“/users”)<br>public class UserServlet extends HttpServlet {</p><p>private UserService userService = new UserService();<br>}</p><p>The same URL mapping can handle different HTTP methods. HttpServlet dispatches GET requests to doGet(), POST requests to doPost(), PUT requests to doPut(), and DELETE requests to doDelete().</p><p>GET /users → doGet()<br>POST /users → doPost()<br>PUT /users → doPut()<br>DELETE /users → doDelete()</p><h3>9. Handling GET Requests</h3><p>The GET endpoint supports two operations: GET /users returns all users, while GET /users?id=1 returns a single user.</p><p>@Override<br>public void doGet(<br> HttpServletRequest request,<br> HttpServletResponse response<br>) throws IOException {</p><p>response.setContentType(“application/json”);</p><p>String idParam = request.getParameter(“id”);</p><p>if (idParam == null) {<br> List&lt;User&gt; users = userService.getAll();</p><p>response.setStatus(200);<br> response.getWriter().write(usersToJson(users));<br> return;<br> }</p><p>Integer id = Integer.parseInt(idParam);<br> User user = userService.getUserById(id);</p><p>if (user == null) {<br> response.setStatus(404);<br> response.getWriter().write(<br> “””<br> {<br> “message”: “User Not Found”<br> }<br> “””<br> );<br> return;<br> }</p><p>response.setStatus(200);<br> response.getWriter().write(userToJson(user));<br>}</p><p>The return statements are important. After returning all users, execution must stop; otherwise the code would continue and try to parse a null id. The same principle applies after writing a 404 response. Once a response branch is complete, processing should not fall through into another response branch.</p><h3>10. Handling POST Requests</h3><p>The POST endpoint creates a user. In this learning project, values are read as request parameters.</p><p>@Override<br>public void doPost(<br> HttpServletRequest request,<br> HttpServletResponse response<br>) throws IOException {</p><p>response.setContentType(“application/json”);</p><p>String idParam = request.getParameter(“id”);<br> String name = request.getParameter(“name”);<br> String email = request.getParameter(“email”);<br> String mobile = request.getParameter(“mobile”);</p><p>if (idParam == null ||<br> name == null ||<br> email == null ||<br> mobile == null) {</p><p>response.setStatus(400);<br> response.getWriter().write(<br> “””<br> {<br> “message”: “Some fields are missing!”<br> }<br> “””<br> );<br> return;<br> }</p><p>Integer id = Integer.parseInt(idParam);</p><p>User user = new User(id, name, email, mobile);<br> User createdUser = userService.createUser(user);</p><p>response.setStatus(201);<br> response.getWriter().write(userToJson(createdUser));<br>}</p><p>The flow is: Tomcat receives POST /users → UserServlet.doPost() reads and validates parameters → a User object is created → UserService stores it → the Servlet returns 201 Created.</p><h3>11. Handling PUT Requests</h3><p>The PUT endpoint updates an existing user. The service returns null when the requested user ID does not exist.</p><p>@Override<br>public void doPut(<br> HttpServletRequest request,<br> HttpServletResponse response<br>) throws IOException {</p><p>response.setContentType(“application/json”);</p><p>Integer id = Integer.parseInt(request.getParameter(“id”));<br> String name = request.getParameter(“name”);<br> String email = request.getParameter(“email”);<br> String mobile = request.getParameter(“mobile”);</p><p>User userToBeUpdated =<br> new User(id, name, email, mobile);</p><p>User updatedUser =<br> userService.updateUser(userToBeUpdated);</p><p>if (updatedUser == null) {<br> response.setStatus(404);<br> response.getWriter().write(<br> “””<br> {<br> “message”: “User Not Found”<br> }<br> “””<br> );<br> return;<br> }</p><p>response.setStatus(200);<br> response.getWriter().write(userToJson(updatedUser));<br>}</p><p>The important control-flow rule appears again: after returning a 404 response, processing stops. Otherwise the method could continue and write a success response as well.</p><h3>12. Handling DELETE Requests</h3><p>The DELETE endpoint removes a user by ID.</p><p>@Override<br>public void doDelete(<br> HttpServletRequest request,<br> HttpServletResponse response<br>) throws IOException {</p><p>response.setContentType(“application/json”);</p><p>Integer id = Integer.parseInt(<br> request.getParameter(“id”)<br> );</p><p>Boolean deleted = userService.deleteRecord(id);</p><p>if (deleted) {<br> response.setStatus(200);<br> response.getWriter().write(<br> “””<br> {<br> “message”: “User Deleted Successfully”<br> }<br> “””<br> );<br> return;<br> }</p><p>response.setStatus(404);<br> response.getWriter().write(<br> “””<br> {<br> “message”: “User Not Found”<br> }<br> “””<br> );<br>}</p><h3>13. Manually Converting Java Objects to JSON</h3><p>To understand response generation clearly, I manually converted User objects into JSON strings.</p><p>private String userToJson(User user) {<br> return “””<br> {<br> “id”: %d,<br> “name”: “%s”,<br> “email”: “%s”,<br> “mobile”: “%s”<br> }<br> “””.formatted(<br> user.getId(),<br> user.getName(),<br> user.getEmail(),<br> user.getMobile()<br> );<br>}</p><p>For a list of users:</p><p>private String usersToJson(List&lt;User&gt; users) {<br> StringBuilder stringBuilder = new StringBuilder();<br> stringBuilder.append(“[“);</p><p>for (int i = 0; i &lt; users.size(); i++) {<br> stringBuilder.append(userToJson(users.get(i)));</p><p>if (i &lt; users.size() — 1) {<br> stringBuilder.append(“,”);<br> }<br> }</p><p>stringBuilder.append(“]”);<br> return stringBuilder.toString();<br>}</p><p>This is useful for learning because the conversion process is visible: Java object → JSON string → response writer → HTTP response. In production applications, JSON libraries or frameworks should normally handle serialization. Manual string construction does not correctly handle every escaping and serialization case.</p><h3>14. Maven Configuration and WAR Packaging</h3><p>The project is packaged as a WAR file using Maven.</p><p>&lt;?xml version=”1.0&quot; encoding=”UTF-8&quot;?&gt;</p><p>&lt;project xmlns=”http://maven.apache.org/POM/4.0.0&quot;<br> xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&quot;<br> xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0<br> http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;</p><p>&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;</p><p>&lt;groupId&gt;com.gautam&lt;/groupId&gt;<br> &lt;artifactId&gt;SeveletCRUDDemo&lt;/artifactId&gt;<br> &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;<br> &lt;packaging&gt;war&lt;/packaging&gt;</p><p>&lt;properties&gt;<br> &lt;maven.compiler.source&gt;21&lt;/maven.compiler.source&gt;<br> &lt;maven.compiler.target&gt;21&lt;/maven.compiler.target&gt;<br> &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br> &lt;/properties&gt;</p><p>&lt;dependencies&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;jakarta.servlet&lt;/groupId&gt;<br> &lt;artifactId&gt;jakarta.servlet-api&lt;/artifactId&gt;<br> &lt;version&gt;6.1.0&lt;/version&gt;<br> &lt;scope&gt;provided&lt;/scope&gt;<br> &lt;/dependency&gt;<br> &lt;/dependencies&gt;</p><p>&lt;build&gt;<br> &lt;finalName&gt;crud-app&lt;/finalName&gt;<br> &lt;/build&gt;</p><p>&lt;/project&gt;</p><p>Two lines are especially important. &lt;packaging&gt;war&lt;/packaging&gt; tells Maven to create a Web Application Archive. The provided dependency scope means the Servlet API is needed to compile the application, while the runtime implementation is supplied by the Servlet Container.</p><h3>15. What Is a WAR File?</h3><p>WAR stands for Web Application Archive. In the traditional deployment model, we build the application and deploy the resulting WAR file to an external Tomcat installation.</p><p>Java Web Application<br> ↓<br> mvn clean package<br> ↓<br> crud-app.war<br> ↓<br> Deploy to Tomcat<br> ↓<br> Tomcat runs the application</p><p>Because the Maven build uses &lt;finalName&gt;crud-app&lt;/finalName&gt;, the generated file is target/crud-app.war. If it is deployed with that name, the application context path is typically /crud-app.</p><p>Because the Servlet mapping is /users, the complete URL is:</p><p><a href="http://localhost:8080/crud-app/users">http://localhost:8080/crud-app/users</a></p><p>Server address: <a href="http://localhost:8080/">http://localhost:8080</a><br>Context path: /crud-app<br>Servlet mapping: /users</p><p>This URL composition is one of the first things to check when debugging a 404 in a traditional Servlet deployment.</p><h3>16. Understanding the Servlet Lifecycle</h3><p>Servlet instances are managed by the Servlet Container. A simplified lifecycle is:</p><p>Servlet class<br> ↓<br>Object creation<br> ↓<br> init()<br> ↓<br> service()<br> ↓<br>GET → doGet()<br>POST → doPost()<br>PUT → doPut()<br>DELETE → doDelete()<br> ↓<br> destroy()</p><p>We normally do not instantiate UserServlet ourselves and call doGet() manually. The container creates and manages the Servlet. Initialization can be lazy or eager depending on configuration. During request processing, HttpServlet routes requests according to the HTTP method. Before removal from service, the container calls destroy() for cleanup.</p><h3>17. Concurrency: One Servlet, Many Requests</h3><p>A Servlet can process many requests concurrently. Tomcat uses request-processing threads, so request-specific data should not be stored carelessly in mutable Servlet instance fields.</p><p>// Dangerous shared mutable state<br>public class UserServlet extends HttpServlet {<br> private String currentUser;<br>}</p><p>A request-local variable is safer for request-specific data:</p><p>@Override<br>public void doGet(<br> HttpServletRequest request,<br> HttpServletResponse response<br>) {<br> String currentUser = request.getParameter(“name”);<br>}</p><p>The sample service also uses a plain HashMap. That is acceptable for illustrating CRUD flow, but a HashMap is not suitable as a production database and is not designed for concurrent writes. Real applications should use proper persistence and concurrency-safe design.</p><h3>18. From Many Servlets to the Front Controller Pattern</h3><p>A small application may have UserServlet, but a larger application may need UserServlet, OrderServlet, ProductServlet, PaymentServlet, AuthenticationServlet, ReportServlet, and many more components.</p><p>As applications grow, directly organizing many request-handling Servlets becomes less convenient. The Front Controller Pattern introduces one central entry point that coordinates request handling. Spring MVC uses this idea through DispatcherServlet.</p><h3>19. Spring MVC and DispatcherServlet</h3><p>In Spring MVC, requests enter the Servlet Container and then pass through DispatcherServlet, which acts as the front controller for the Spring MVC request-processing pipeline.</p><p>Client<br> ↓<br>HTTP Request<br> ↓<br>Tomcat<br> ↓<br>DispatcherServlet<br> ↓<br>Matching Controller<br> ↓<br>Service<br> ↓<br>Repository<br> ↓<br>Database</p><p>Instead of writing UserServlet, OrderServlet, and ProductServlet as the main application request handlers, we typically create UserController, OrderController, and ProductController.</p><h3>20. From UserServlet to UserController</h3><p>A Servlet handles HTTP methods by overriding doGet(), doPost(), doPut(), and doDelete(). Spring MVC provides a higher-level controller model.</p><p>@RestController<br>@RequestMapping(“/users”)<br>public class UserController {</p><p>private final UserService userService;</p><p>public UserController(UserService userService) {<br> this.userService = userService;<br> }</p><p>@GetMapping<br> public List&lt;User&gt; getAll() {<br> return userService.getAll();<br> }</p><p>@GetMapping(“/{id}”)<br> public User getById(@PathVariable Integer id) {<br> return userService.getUserById(id);<br> }</p><p>@PostMapping<br> public User create(@RequestBody User user) {<br> return userService.createUser(user);<br> }</p><p>@PutMapping(“/{id}”)<br> public User update(<br> @PathVariable Integer id,<br> @RequestBody User user<br> ) {<br> return userService.updateUser(user);<br> }</p><p>@DeleteMapping(“/{id}”)<br> public void delete(@PathVariable Integer id) {<br> userService.deleteRecord(id);<br> }<br>}</p><p>The conceptual difference is easier to see after writing the Servlet version. In the Servlet approach, we manually read parameters, branch inside request methods, set status codes, and write response bodies. In Spring MVC, routing, argument binding, and response conversion can be handled by the framework.</p><h3>21. What Does DispatcherServlet Actually Do?</h3><p>Suppose a client sends GET /users/10. The conceptual flow is:</p><p>Client<br> ↓<br>GET /users/10<br> ↓<br>Tomcat<br> ↓<br>DispatcherServlet<br> ↓<br>Find matching handler<br> ↓<br>UserController.getById(10)<br> ↓<br>UserService.getUserById(10)<br> ↓<br>Repository<br> ↓<br>Database</p><p>DispatcherServlet does not replace Tomcat. Tomcat provides the server and Servlet Container runtime. DispatcherServlet is itself part of the Spring web application and coordinates Spring MVC request handling inside that environment.</p><h3>22. External Tomcat vs Embedded Tomcat</h3><p>The traditional Servlet deployment model is application → WAR → external Tomcat. Spring Boot commonly uses an embedded server model in which the application is packaged with the server dependencies and started as one executable application.</p><p>Traditional deployment:</p><p>Application<br> ↓<br>Build WAR<br> ↓<br>External Tomcat<br> ↓<br>Deploy and run</p><p>Typical Spring Boot deployment:</p><p>Spring Boot Application<br>├── Application Code<br>├── Spring MVC<br>├── DispatcherServlet<br>└── Embedded Tomcat</p><p>Run:<br>java -jar application.jar</p><p>Spring Boot does not eliminate the web server. It changes how the server is configured, packaged, and started.</p><h3>23. What This Project Made Clear</h3><p>Before building the Servlet version, Spring MVC annotations looked like shortcuts. After implementing similar behavior manually, their value became much clearer.</p><p>Servlet:<br>request.getParameter(“id”);</p><p>Spring MVC:<br>@RequestParam Integer id<br>or<br>@PathVariable Integer id</p><p>Servlet:<br>response.getWriter().write(userToJson(user));</p><p>Spring MVC:<br>return user;</p><p>Servlet:<br>doGet()<br>doPost()<br>doPut()<br>doDelete()</p><p>Spring MVC:<br>@GetMapping<br>@PostMapping<br>@PutMapping<br>@DeleteMapping</p><p>Framework abstractions are easier to understand when we know what they are abstracting.</p><h3>24. A Simple Mental Model</h3><p>I now think about the Java web stack in layers:</p><p>Socket<br> → Low-level network communication</p><p>HTTP<br> → Web communication protocol</p><p>Servlet API<br> → Java programming model for HTTP requests and responses</p><p>Tomcat<br> → Web server and Servlet Container runtime</p><p>Spring MVC<br> → Controller-based web architecture</p><p>DispatcherServlet<br> → Central front controller for Spring MVC</p><p>Spring Boot<br> → Convenient configuration, packaging, and application startup</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be95856802c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot REST API Architecture Explained: Controller, Service, Repository, Entity, JPA &…]]></title>
            <link>https://medium.com/@suparngautam/spring-boot-rest-api-architecture-explained-controller-service-repository-entity-jpa-95f8a7092067?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/95f8a7092067</guid>
            <category><![CDATA[rest-api-architecture]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 04:34:56 GMT</pubDate>
            <atom:updated>2026-07-01T04:34:56.856Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Boot REST API Architecture Explained: Controller, Service, Repository, Entity, JPA &amp; ResponseEntity</h3><p>When learning Spring Boot, you’ll repeatedly encounter terms like <strong>Controller</strong>, <strong>Service</strong>, <strong>Repository</strong>, <strong>Entity</strong>, <strong>JPA</strong>, and <strong>ResponseEntity</strong>. Understanding how these components work together is essential for building clean, maintainable, and scalable REST APIs.</p><p>This article explains the complete request flow, each layer’s responsibility, and how to return proper HTTP responses using ResponseEntity.</p><h3>Spring Boot Architecture</h3><p>A typical Spring Boot REST application follows a layered architecture.</p><pre>Client (Postman / Browser)<br>        │<br>   HTTP Request<br>        │<br>        ▼<br>Controller<br>        │<br>        ▼<br>Service<br>        │<br>        ▼<br>Repository<br>        │<br>        ▼<br>Database (MySQL)</pre><p>Once the database processes the request, the response travels back through the same layers in reverse order.</p><pre>Database<br>   ▲<br>Repository<br>   ▲<br>Service<br>   ▲<br>Controller<br>   ▲<br>HTTP Response<br>   ▲<br>Client</pre><p>Each layer has a specific responsibility, making the application easier to maintain and test.</p><h3>1. Controller Layer</h3><p>The <strong>Controller</strong> is the entry point of every HTTP request.</p><p>Its responsibilities include:</p><ul><li>Receiving HTTP requests</li><li>Reading request parameters or JSON data</li><li>Validating incoming data (basic validation)</li><li>Calling the Service layer</li><li>Returning an HTTP response</li></ul><h3>Example</h3><pre>@RestController<br>@RequestMapping(&quot;/api/students&quot;)<br>public class StudentController {<br><br>    private StudentService studentService;<br>    public StudentController(StudentService studentService){<br>    this.studentService=studentService;<br>    }<br>    @PostMapping<br>    public ResponseEntity&lt;Student&gt; createStudent(<br>            @RequestBody Student student) {<br>        Student saved = studentService.create(student);<br>        return ResponseEntity.ok(saved);<br>    }<br>}</pre><h3>Important Rule</h3><p>The controller <strong>should not contain business logic</strong>.</p><p>Avoid writing code like:</p><pre>if(student.getAge() &lt; 18){<br>    ...<br>}</pre><p>Such logic belongs in the Service layer.</p><h3>2. Service Layer</h3><p>The <strong>Service</strong> contains the application’s business logic.</p><p>It acts as a bridge between the Controller and Repository.</p><p>Example:</p><pre>@Service<br>public class StudentService {</pre><pre>    @Autowired<br>    private StudentRepository repository;</pre><pre>    public Student create(Student student) {<br>        return repository.save(student);<br>    }<br>}</pre><h3>Examples of Business Logic</h3><ul><li>Age must be greater than 18</li><li>Email must be unique</li><li>Password should be encrypted</li><li>Salary should not be negative</li><li>Generate invoice numbers</li><li>Apply discounts</li></ul><p>Business rules should always remain inside the Service layer.</p><h3>3. Repository Layer</h3><p>The Repository is responsible for communicating with the database.</p><p>Example:</p><pre>@Repository<br>public interface StudentRepository<br>        extends JpaRepository&lt;Student, Long&gt; {}</pre><p>Because it extends JpaRepository, Spring Data JPA automatically provides many useful methods.</p><pre>save()<br>findById()<br>findAll()<br>deleteById()<br>existsById()<br>count()</pre><p>No SQL queries are required for these common operations.</p><p>Instead of writing:</p><pre>SELECT * FROM students;</pre><p>You simply write:</p><pre>repository.findAll();</pre><h3>4. Entity</h3><p>An <strong>Entity</strong> represents a database table.</p><p>Example:</p><pre>@Entity<br>@Table(name = &quot;students&quot;)<br>public class Student {<br>@Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String name;<br>    private Integer age;<br>    private String email;<br>}</pre><p>Spring Data JPA maps this Java class into a database table.</p><p>Equivalent SQL:</p><pre>CREATE TABLE students(<br>id BIGINT PRIMARY KEY,<br>name VARCHAR(255),<br>age INT,<br>email VARCHAR(255)<br>);</pre><p>Each object of the class represents one row in the table.</p><h3>5. HTTP Methods (CRUD Operations)</h3><p>REST APIs mainly use four HTTP methods.</p><h3>Create</h3><pre>POST /api/students</pre><p>Request Body</p><pre>{<br>  &quot;name&quot;:&quot;Rahul&quot;,<br>  &quot;age&quot;:22,<br>  &quot;email&quot;:&quot;rahul@gmail.com&quot;<br>}</pre><p>Creates a new student.</p><h3>Read One</h3><pre>GET /api/students/1</pre><p>Returns the student whose ID is 1.</p><h3>Read All</h3><pre>GET /api/students</pre><p>Returns all students.</p><h3>Update</h3><pre>PUT /api/students/1</pre><p>Updates the existing student.</p><h3>Delete</h3><pre>DELETE /api/students/1</pre><p>Deletes the student.</p><h3>6. Understanding @RequestBody</h3><p>Suppose Postman sends this JSON.</p><pre>{<br>  &quot;name&quot;:&quot;Amit&quot;,<br>  &quot;age&quot;:20,<br>  &quot;email&quot;:&quot;amit@gmail.com&quot;<br>}</pre><p>Controller:</p><pre>@PostMapping<br>public void create(<br>        @RequestBody Student student){<br>}</pre><p>Spring Boot automatically converts the JSON into a Java object.</p><pre>JSON</pre><pre>↓</pre><pre>Student Object</pre><p>So,</p><pre>{<br>&quot;name&quot;:&quot;Rahul&quot;<br>}</pre><p>becomes</p><pre>student.getName();</pre><p>This conversion is performed automatically by <strong>Jackson</strong>, the default JSON library used by Spring Boot.</p><h3>7. ORM (Object Relational Mapping)</h3><p>ORM stands for <strong>Object Relational Mapping</strong>.</p><p>Without ORM, you manually write SQL.</p><pre>INSERT INTO students(name, age, email)<br>VALUES(&#39;Rahul&#39;,22,&#39;rahul@gmail.com&#39;);</pre><p>With JPA and Hibernate, you simply write:</p><pre>repository.save(student);</pre><p>Hibernate automatically generates the required SQL behind the scenes.</p><p>The mapping is simple:</p><pre>Java Object</pre><pre>↓</pre><pre>Database Row</pre><p>This reduces boilerplate code and makes development much faster.</p><h3>8. Why Entity is NOT a Spring Component</h3><p>Many beginners think @Entity works like @Service or @Controller.</p><p>It does not.</p><p>Spring Components:</p><pre>@Controller<br>@Service<br>@Repository<br>@Component</pre><p>These are managed by the <strong>Spring IoC Container</strong>.</p><p>An Entity, however, is managed by <strong>JPA/Hibernate</strong>, not directly by Spring IoC.</p><p>Its purpose is only to represent database data.</p><h3>9. Complete CRUD Flow</h3><p>Whenever a client sends a request, the execution follows this path.</p><pre>Postman<br>↓</pre><pre>Controller</pre><pre>↓</pre><pre>Service</pre><pre>↓</pre><pre>Repository</pre><pre>↓</pre><pre>Hibernate</pre><pre>↓</pre><pre>MySQL</pre><p>The response then travels back.</p><pre>MySQL<br>↓</pre><pre>Hibernate</pre><pre>↓</pre><pre>Repository</pre><pre>↓</pre><pre>Service</pre><pre>↓</pre><pre>Controller</pre><pre>↓</pre><pre>Postman</pre><p>This separation of responsibilities keeps the application clean and maintainable.</p><h3>10. Understanding ResponseEntity</h3><p>Normally, you can simply return an object.</p><pre>return student;</pre><p>Spring automatically sends:</p><pre>HTTP Status: 200 OK</pre><p>However, REST APIs often need more control.</p><p>Sometimes you need to customize:</p><ul><li>HTTP Status Code</li><li>Response Headers</li><li>Response Body</li></ul><p>For this purpose, Spring provides ResponseEntity.</p><p>Example:</p><pre>@GetMapping(&quot;/{id}&quot;)<br>public ResponseEntity&lt;Student&gt; getStudent(<br>        @PathVariable Long id){</pre><pre>    Student student = service.get(id);</pre><pre>    return ResponseEntity.ok(student);<br>}</pre><p>Response:</p><pre>Status : 200 OK</pre><pre>{<br>  &quot;name&quot;:&quot;Rahul&quot;<br>}</pre><h3>11. Returning 201 Created</h3><p>When a new resource is successfully created, the HTTP specification recommends returning:</p><pre>201 Created</pre><p>instead of</p><pre>200 OK</pre><p>Spring provides:</p><pre>ResponseEntity.created(...)</pre><p>But it requires a URI.</p><p>Example:</p><pre>URI location =<br>    URI.create(&quot;/api/students/&quot; + saved.getId());</pre><pre>return ResponseEntity<br>        .created(location)<br>        .body(saved);</pre><p>Response:</p><pre>HTTP 201 Created</pre><p>Headers</p><pre>Location:<br>/api/students/15</pre><p>Body</p><pre>{<br>    &quot;id&quot;:15,<br>    &quot;name&quot;:&quot;Rahul&quot;<br>}</pre><h3>Why is the URI Required?</h3><p>The HTTP specification recommends that when a server creates a new resource, it should tell the client where that resource can be accessed.</p><p>This is done using the <strong>Location</strong> header.</p><p>For example:</p><pre>POST /students</pre><p>creates</p><pre>Student ID = 15</pre><p>The server responds with:</p><pre>HTTP/1.1 201 Created</pre><pre>Location:<br>/api/students/15</pre><p>This allows the client to immediately know where the newly created resource exists.</p><h3>12. Returning 201 Without a URI</h3><p>Sometimes you don’t want to expose or calculate the resource URI.</p><p>In such cases, you can still return HTTP 201.</p><p>Example:</p><pre>return ResponseEntity<br>        .status(HttpStatus.CREATED)<br>        .body(savedStudent);</pre><p>or</p><pre>return new ResponseEntity&lt;&gt;(<br>        savedStudent,<br>        HttpStatus.CREATED<br>);</pre><p>Response:</p><pre>Status : 201 Created</pre><pre>Body : Student Object</pre><p>No Location header is included.</p><p>This approach is perfectly acceptable for many APIs.</p><h3>13. Common ResponseEntity Methods</h3><h3>200 OK</h3><pre>return ResponseEntity.ok(student);</pre><h3>201 Created (Recommended)</h3><pre>URI uri =<br>    URI.create(&quot;/api/students/&quot; + student.getId());</pre><pre>return ResponseEntity<br>        .created(uri)<br>        .body(student);</pre><h3>201 Created (Without URI)</h3><pre>return ResponseEntity<br>        .status(HttpStatus.CREATED)<br>        .body(student);</pre><h3>204 No Content</h3><p>Typically used after a successful delete operation.</p><pre>return ResponseEntity.noContent().build();</pre><h3>400 Bad Request</h3><pre>return ResponseEntity<br>        .badRequest()<br>        .body(&quot;Invalid data&quot;);</pre><h3>404 Not Found</h3><pre>return ResponseEntity<br>        .status(HttpStatus.NOT_FOUND)<br>        .body(&quot;Student not found&quot;);</pre><h3>500 Internal Server Error</h3><pre>return ResponseEntity<br>        .status(HttpStatus.INTERNAL_SERVER_ERROR)<br>        .body(&quot;Something went wrong&quot;);</pre><h3>14. Which Response Should You Use?</h3><p>OperationRecommended ResponseGETResponseEntity.ok(data) → <strong>200 OK</strong>POSTResponseEntity.created(uri).body(data) → <strong>201 Created</strong> + Location headerPOST (No URI)ResponseEntity.status(HttpStatus.CREATED).body(data) → <strong>201 Created</strong>PUTResponseEntity.ok(updatedData) → <strong>200 OK</strong>DELETEResponseEntity.noContent().build() → <strong>204 No Content</strong></p><p>These are the response patterns commonly used in professional Spring Boot REST APIs.</p><h3>Key Takeaways</h3><ul><li>Follow the layered architecture: <strong>Controller → Service → Repository → Database</strong>.</li><li>Keep controllers lightweight and move all business rules to the Service layer.</li><li>Use Entities to represent database tables.</li><li>Let Spring Data JPA and Hibernate handle SQL generation through ORM.</li><li>Use @RequestBody to automatically convert JSON into Java objects.</li><li>Prefer ResponseEntity when you need control over HTTP status codes, headers, or response bodies.</li><li>Return <strong>201 Created</strong> after successful resource creation, ideally with a <strong>Location</strong> header pointing to the newly created resource.</li><li>Choose appropriate HTTP status codes (200, 201, 204, 400, 404, 500) to make your REST APIs more consistent and standards-compliant.</li></ul><p>By following these practices, you’ll build REST APIs that are clean, maintainable, and aligned with industry standards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95f8a7092067" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Externalized Configuration, @Value, @ConfigurationProperties, and ApplicationRunner]]></title>
            <link>https://medium.com/@suparngautam/understanding-externalized-configuration-value-configurationproperties-and-applicationrunner-18f387055866?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/18f387055866</guid>
            <category><![CDATA[configuration-properties]]></category>
            <category><![CDATA[understand-app-prop]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 08:19:07 GMT</pubDate>
            <atom:updated>2026-06-27T08:19:07.932Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the biggest advantages of Spring Boot is its ability to simplify application development through intelligent configuration and minimal boilerplate code. Instead of hardcoding values inside Java classes, Spring Boot encourages developers to keep configurations external and provides several ways to access them efficiently.</p><p>In this article, I’ll share my notes and understanding of some essential Spring Boot concepts, including <strong>configuration files</strong>, <strong>property injection</strong>, and <strong>executing code during application startup</strong>.</p><h3>Why Externalized Configuration?</h3><p>In traditional Java applications, developers often hardcode values such as database credentials, server ports, or API URLs directly inside Java classes.</p><pre>String username = &quot;root&quot;;<br>String password = &quot;root&quot;;</pre><p>This approach has several drawbacks:</p><ul><li>Configuration changes require recompiling the application.</li><li>Managing different environments (Development, Testing, Production) becomes difficult.</li><li>Sensitive information may accidentally become part of the source code.</li></ul><p>Spring Boot solves this problem by allowing us to store configuration outside Java code.</p><h3>application.properties</h3><p>The most commonly used configuration file in Spring Boot is <strong>application.properties</strong>.</p><p>It is a <strong>non-Java configuration file</strong> that follows a simple key-value format.</p><p>Example:</p><pre>spring.application.name=StudentManagement<br>server.port=8081<br>spring.datasource.url=jdbc:mysql://localhost:3306/studentdb<br>spring.datasource.username=root<br>spring.datasource.password=root</pre><p>Every configuration follows the format:</p><pre>key=value</pre><p>For example:</p><pre>server.port=8080</pre><p>Here,</p><ul><li><strong>Key:</strong> server.port</li><li><strong>Value:</strong> 8080</li></ul><p>Spring Boot automatically reads this file during application startup, so developers don’t need to load it manually.</p><h3>application.yml</h3><p>Spring Boot also supports YAML configuration through <strong>application.yml</strong>.</p><p>Instead of writing:</p><pre>server.port=8080<br>spring.datasource.username=root<br>spring.datasource.password=root</pre><p>you can write:</p><pre>server:<br>  port: 8080<br>spring:<br>  datasource:<br>    username: root<br>    password: root</pre><p>Both files serve the same purpose. The only difference is the syntax.</p><p>Many developers prefer YAML because nested configurations are easier to read.</p><h3>Other Configuration Sources</h3><p>Spring Boot doesn’t rely only on configuration files. It can also load values from multiple sources, including:</p><ul><li>application.properties</li><li>application.yml</li><li>Environment Variables</li><li>System Properties</li><li>Command-Line Arguments</li></ul><p>Spring Boot follows a priority order, where higher-priority sources override lower-priority ones.</p><p>For example, if application.properties contains:</p><pre>server.port=8080</pre><p>Running the application like this:</p><pre>java -jar app.jar --server.port=9090</pre><p>will start the application on port <strong>9090</strong>, because command-line arguments have higher priority.</p><h3>Reading Properties with @Value</h3><p>After defining configuration values, the next step is accessing them inside Java classes.</p><p>Spring Boot provides the @Value annotation for this purpose.</p><p>Suppose application.properties contains:</p><pre>app.name=SpringBootDemo</pre><p>You can access it using:</p><pre>@Component<br>public class DemoService {<br>@Value(&quot;${app.name}&quot;)<br>    private String appName;<br>}</pre><p>Spring automatically injects the value into the field.</p><h3>Providing Default Values</h3><p>Sometimes a property may not exist.</p><p>Instead of throwing an error, we can provide a default value.</p><p>Example:</p><pre>@Value(&quot;${payment.gateway:gpay}&quot;)<br>private String paymentGateway;</pre><p>If the property exists:</p><pre>payment.gateway=PhonePe</pre><p>Output:</p><pre>PhonePe</pre><p>If it doesn’t exist:</p><pre>gpay</pre><p>This helps make applications more flexible and fault-tolerant.</p><h3>The Limitation of @Value</h3><p>Using @Value is convenient when reading only a few properties.</p><p>However, imagine an application with many related configurations.</p><pre>employee.name=Rahul<br>employee.age=24<br>employee.city=Delhi<br>employee.phone=9876543210<br>employee.department=IT<br>employee.salary=50000</pre><p>Using multiple @Value annotations becomes repetitive.</p><pre>@Value(&quot;${employee.name}&quot;)<br>private String name;<br><br>@Value(&quot;${employee.age}&quot;)<br>private int age;<br><br>@Value(&quot;${employee.city}&quot;)<br>private String city;<br><br>@Value(&quot;${employee.phone}&quot;)<br>private String phone;</pre><p>As the number of properties increases, maintaining the code becomes difficult.</p><h3>Using @ConfigurationProperties</h3><p>Spring Boot provides a cleaner solution through @ConfigurationProperties.</p><p>Instead of injecting each property individually, we can map an entire group of related properties into a single class.</p><p>Configuration:</p><pre>employee.name=Rahul<br>employee.age=24<br>employee.city=Delhi</pre><p>Java class:</p><pre>@Component<br>@ConfigurationProperties(prefix = &quot;employee&quot;)<br>public class EmployeeProperties {<br>private String name;<br>    private int age;<br>    private String city;<br>    // Getters and Setters<br>}</pre><p>Spring automatically maps:</p><ul><li>employee.name → name</li><li>employee.age → age</li><li>employee.city → city</li></ul><p>This approach keeps configuration organized and improves code readability.</p><h3>Advantages of @ConfigurationProperties</h3><ul><li>Cleaner code</li><li>Better maintainability</li><li>Type-safe configuration</li><li>Groups related properties together</li><li>Easier to manage in large projects</li></ul><p>Because of these benefits, it is the preferred approach whenever multiple related properties are involved.</p><h3>Running Code After Spring Boot Starts</h3><p>Sometimes we need to execute certain tasks immediately after the application starts.</p><p>Examples include:</p><ul><li>Loading initial data</li><li>Initializing caches</li><li>Printing startup information</li><li>Verifying database connectivity</li></ul><p>Spring Boot provides the ApplicationRunner interface for this purpose.</p><p>Example:</p><pre>@Component<br>public class DemoRunner implements ApplicationRunner {<br>@Override<br>    public void run(ApplicationArguments args) throws Exception {<br>        System.out.println(&quot;Application Started Successfully!&quot;);<br>    }<br>}</pre><p>The run() method is automatically executed once the Spring Boot application has completed startup.</p><h3>Understanding ApplicationArguments</h3><p>The run() method receives an ApplicationArguments object.</p><pre>public void run(ApplicationArguments args)</pre><p>This object contains all command-line arguments passed while starting the application.</p><p>Example:</p><pre>java -jar demo.jar --name=Rahul --city=Delhi</pre><p>Inside the application:</p><pre>args.getOptionValues(&quot;name&quot;);</pre><p>returns:</p><pre>Rahul</pre><p>This makes it easier to read startup arguments without manually parsing them.</p><h3>ApplicationRunner vs CommandLineRunner</h3><p>Spring Boot provides two startup interfaces.</p><p>CommandLineRunnerApplicationRunnerReceives String... argsReceives ApplicationArgumentsSimplerMore feature-richManual parsingBuilt-in option parsing</p><p>Both execute after the application starts, but ApplicationRunner is generally preferred because it offers a more structured way to access command-line arguments.</p><h3>Conclusion</h3><p>Externalized configuration is one of the key features that makes Spring Boot applications flexible and production-ready. By moving configuration outside Java code, applications become easier to maintain, deploy, and manage across different environments.</p><p>Instead of relying heavily on @Value, developers should prefer @ConfigurationProperties for managing groups of related settings. Additionally, ApplicationRunner provides a simple and effective way to execute initialization logic immediately after application startup.</p><p>Mastering these concepts will help you build cleaner, more maintainable Spring Boot applications and strengthen your understanding of how real-world Spring Boot projects are configured.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18f387055866" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding @SpringBootApplication: The Heart of Every Spring Boot Application]]></title>
            <link>https://medium.com/@suparngautam/understanding-springbootapplication-the-heart-of-every-spring-boot-application-b0ec07ae4352?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0ec07ae4352</guid>
            <category><![CDATA[spring-boot-application]]></category>
            <category><![CDATA[auto-configuration]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Sat, 27 Jun 2026 05:44:48 GMT</pubDate>
            <atom:updated>2026-06-27T05:44:48.084Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started learning Spring Boot, one annotation appeared in almost every project:</p><pre>@SpringBootApplication</pre><p>At first glance, it looks like just another annotation. However, this single annotation hides some of the most powerful features of Spring Boot.</p><p>In this article, we’ll explore what @SpringBootApplication actually does, how Spring Boot starts an application, and how it automatically configures everything behind the scenes.</p><h3>Spring Framework vs Spring Boot</h3><p>Before Spring Boot, developers used the Spring Framework, where application configuration was typically done in two ways:</p><ul><li><strong>XML-based Configuration</strong></li><li><strong>Annotation-based Configuration</strong></li></ul><h3>XML Configuration</h3><pre>&lt;bean id=&quot;userService&quot; class=&quot;com.example.UserService&quot;/&gt;</pre><h3>Annotation Configuration</h3><pre>@Component<br>public class UserService {<br>}</pre><p>Managing XML files became tedious as projects grew larger. Spring Boot solved this problem by embracing annotation-based configuration and sensible defaults.</p><h3>Starting a Spring Boot Application</h3><p>Every Spring Boot application starts with a main class similar to this:</p><pre>@SpringBootApplication<br>public class DemoApplication {<br>public static void main(String[] args) {<br>        SpringApplication.run(DemoApplication.class, args);<br>    }<br>}</pre><p>The most important line is:</p><pre>SpringApplication.run(DemoApplication.class, args);</pre><p>This single method performs multiple tasks:</p><ul><li>Creates the IoC (Inversion of Control) Container</li><li>Scans the project for Spring components</li><li>Creates and manages beans</li><li>Performs Dependency Injection</li><li>Applies Auto Configuration</li><li>Starts the embedded Tomcat server (for web applications)</li></ul><p>Instead of writing hundreds of configuration lines manually, Spring Boot does everything automatically.</p><h3>What Does @SpringBootApplication Mean?</h3><p>Many beginners think it’s a single annotation, but it’s actually a combination of three annotations.</p><pre>@SpringBootApplication</pre><p>is equivalent to</p><pre>@Configuration<br>@EnableAutoConfiguration<br>@ComponentScan</pre><p>Each one has a specific responsibility.</p><h3>1. @Configuration</h3><p>A configuration class tells Spring:</p><blockquote><em>“This class contains bean definitions.”</em></blockquote><p>Example:</p><pre>@Configuration<br>public class AppConfig {<br>@Bean<br>    public User user() {<br>        return new User();<br>    }<br>}</pre><p>When Spring starts, it executes the user() method once and stores the returned object inside the IoC container.</p><p>Since @SpringBootApplication already includes @Configuration, your main class is also a configuration class.</p><p>That’s why this works perfectly:</p><pre>@SpringBootApplication<br>public class DemoApplication {<br>@Bean<br>    public User user() {<br>        return new User();<br>    }<br>}</pre><h3>2. @ComponentScan</h3><p>Spring Boot automatically scans the package where the main class is located.</p><p>Suppose your project structure looks like this:</p><pre>com.example<br>│<br>├── DemoApplication<br>├── controller<br>├── service<br>├── repository</pre><p>Spring Boot scans every sub-package under com.example.</p><p>Whenever it finds annotations like</p><ul><li>@Component</li><li>@Service</li><li>@Repository</li><li>@Controller</li><li>@RestController</li></ul><p>it automatically creates beans for them.</p><p>For example:</p><pre>@Service<br>public class UserService {<br>}</pre><p>You never need to create this object manually.</p><h3>Scanning Other Packages</h3><p>If your classes are located outside the main package, you can specify additional packages.</p><pre>@SpringBootApplication(<br>    scanBasePackages = {<br>        &quot;com.example&quot;,<br>        &quot;com.project.services&quot;<br>    }<br>)</pre><h3>3. @EnableAutoConfiguration</h3><p>This is one of the biggest reasons developers love Spring Boot.</p><p>Instead of asking developers to configure every library manually, Spring Boot examines the project’s dependencies and configures everything automatically.</p><p>For example, adding this dependency</p><pre>spring-boot-starter-web</pre><p>automatically configures:</p><ul><li>Embedded Tomcat</li><li>DispatcherServlet</li><li>Spring MVC</li><li>Jackson</li><li>JSON converters</li><li>Error handling</li></ul><p>Similarly,</p><pre>spring-boot-starter-data-jpa</pre><p>automatically configures:</p><ul><li>Hibernate</li><li>EntityManager</li><li>Transaction Manager</li><li>DataSource</li></ul><p>No additional configuration is required in most cases.</p><h3>@Component vs @Bean</h3><p>One of the most common interview questions is the difference between these two annotations.</p><h3>@Component</h3><p>Used on a class.</p><pre>@Component<br>public class UserService {<br>}</pre><p>Spring creates the object automatically.</p><h3>@Bean</h3><p>Used on methods inside a configuration class.</p><pre>@Configuration<br>public class AppConfig {<br>@Bean<br>    public User user() {<br>        return new User();<br>    }<br>}</pre><p>This approach is generally used when creating objects for third-party libraries that you cannot modify.</p><h3>Why Is Spring Boot Called an Opinionated Framework?</h3><p>Spring Boot follows the principle of <strong>Convention over Configuration</strong>.</p><p>Instead of asking developers how everything should be configured, it makes sensible assumptions.</p><p>For example, when you add:</p><pre>spring-boot-starter-web</pre><p>Spring Boot assumes you are building a web application and automatically configures everything required to run it.</p><p>This dramatically reduces boilerplate code.</p><h3>How Does Auto Configuration Work?</h3><p>Imagine adding this dependency:</p><pre>spring-boot-starter-web</pre><p>Behind the scenes, Spring Boot performs checks like:</p><pre>Is Spring MVC available?</pre><pre>Yes</pre><pre>↓</pre><pre>Configure DispatcherServlet</pre><pre>↓</pre><pre>Is Jackson available?</pre><pre>Yes</pre><pre>↓</pre><pre>Create ObjectMapper Bean</pre><pre>↓</pre><pre>Is Tomcat available?</pre><pre>Yes</pre><pre>↓</pre><pre>Start Embedded Tomcat</pre><p>Everything happens automatically.</p><h3>Conditional Auto Configuration</h3><p>Spring Boot doesn’t create every bean blindly.</p><p>Instead, it uses conditional annotations.</p><h3>@ConditionalOnClass</h3><p>Creates a bean only if a particular class exists.</p><pre>@Bean<br>@ConditionalOnClass(ObjectMapper.class)<br>public JsonParser parser() {<br>    return new JacksonJsonParser();<br>}</pre><p>If ObjectMapper is available in the classpath, the bean is created.</p><p>Otherwise, it is skipped.</p><h3>@ConditionalOnMissingBean</h3><p>Creates a bean only if another bean of the same type does not already exist.</p><pre>@Bean<br>@ConditionalOnMissingBean<br>public ObjectMapper objectMapper() {<br>    return new ObjectMapper();<br>}</pre><p>If you already defined your own ObjectMapper, Spring Boot won&#39;t create another one.</p><p>This allows developers to override Spring Boot’s default configuration whenever necessary.</p><h3>What Happens When the Application Starts?</h3><p>The complete startup flow looks like this:</p><pre>main()</pre><pre>↓</pre><pre>SpringApplication.run()</pre><pre>↓</pre><pre>Create IoC Container</pre><pre>↓</pre><pre>Component Scan</pre><pre>↓</pre><pre>Find Components</pre><pre>↓</pre><pre>Create Beans</pre><pre>↓</pre><pre>Perform Dependency Injection</pre><pre>↓</pre><pre>Apply Auto Configuration</pre><pre>↓</pre><pre>Start Embedded Tomcat</pre><pre>↓</pre><pre>Application Ready</pre><h3>Key Takeaways</h3><ul><li>@SpringBootApplication combines three annotations:</li><li>@Configuration</li><li>@EnableAutoConfiguration</li><li>@ComponentScan</li><li>SpringApplication.run() initializes the entire Spring Boot application.</li><li>@ComponentScan automatically discovers Spring-managed classes.</li><li>@Configuration and @Bean define custom beans.</li><li>@EnableAutoConfiguration configures libraries automatically based on project dependencies.</li><li>Conditional annotations like @ConditionalOnClass and @ConditionalOnMissingBean ensure beans are only created when appropriate.</li><li>Spring Boot minimizes boilerplate configuration and allows developers to focus on writing business logic.</li></ul><h3>Final Thoughts</h3><p>Spring Boot’s biggest strength is that it removes the complexity of application setup. Instead of manually configuring servers, serializers, data sources, and dozens of beans, developers simply add the required dependencies, and Spring Boot handles the rest.</p><p>Understanding how @SpringBootApplication works internally is one of the most important milestones in mastering Spring Boot. Once these concepts become clear, advanced topics such as Spring MVC, Spring Data JPA, Spring Security, and Microservices become much easier to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0ec07ae4352" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Core Deep Dive: IoC Container, Beans, XML Configuration, Dependency Injection, Scopes…]]></title>
            <link>https://medium.com/@suparngautam/spring-core-deep-dive-ioc-container-beans-xml-configuration-dependency-injection-scopes-3cf95343c82e?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cf95343c82e</guid>
            <category><![CDATA[spring-xml-configuration]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Thu, 25 Jun 2026 12:29:26 GMT</pubDate>
            <atom:updated>2026-06-25T12:29:26.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spring Core Deep Dive: IoC Container, Beans, XML Configuration, Dependency Injection, Scopes, Lifecycle &amp; Collections</h3><h3>Introduction</h3><p>Before Spring Boot became the standard for building Java applications, Spring developers heavily relied on XML-based configuration to define and manage beans. Understanding XML configuration is still important because it helps us understand the fundamentals of Spring’s IoC (Inversion of Control) Container and Dependency Injection mechanism.</p><p>In this article, we’ll explore:</p><ul><li>IoC Container</li><li>Configuration Metadata</li><li>Bean Creation</li><li>Bean Retrieval</li><li>Dependency Injection</li><li>Constructor Injection</li><li>Setter Injection</li><li>Multiple Beans of Same Type</li><li>Bean Scopes</li><li>Collection Injection</li><li>Bean Lifecycle</li><li>XML File Modularization</li></ul><p>Let’s begin.</p><h3>What is IoC (Inversion of Control)?</h3><p>Traditionally, objects are created manually:</p><pre>OrderService orderService = new OrderService();</pre><p>In Spring, object creation and dependency management are handled by the framework itself.</p><p>This concept is known as <strong>Inversion of Control (IoC)</strong>.</p><p>Instead of developers controlling object creation, Spring takes over that responsibility.</p><p>The component responsible for this is called the <strong>IoC Container</strong>.</p><h3>Configuration Metadata</h3><p>The IoC Container needs instructions about:</p><ul><li>Which objects (beans) to create</li><li>How to create them</li><li>Which dependencies to inject</li></ul><p>These instructions are called <strong>Configuration Metadata</strong>.</p><p>Spring supports two major approaches:</p><h3>1. XML-Based Configuration</h3><pre>&lt;bean id=&quot;orderService&quot;<br>      class=&quot;com.gautam.OrderService&quot;/&gt;</pre><h3>2. Annotation-Based Configuration</h3><pre>@Component<br>@Service<br>@Repository<br>@Configuration<br>@Bean</pre><p>Modern Spring applications mostly use annotations, but understanding XML helps build a strong foundation.</p><h3>Creating a Bean in XML</h3><p>A bean is simply an object managed by Spring.</p><p>Example:</p><pre>&lt;bean id=&quot;orderService&quot;<br>      class=&quot;com.gautam.OrderService&quot;/&gt;</pre><h3>Attributes</h3><h4>id</h4><p>Unique identifier of the bean.</p><pre>id=&quot;orderService&quot;</pre><h4>class</h4><p>Fully qualified class name.</p><pre>class=&quot;com.gautam.OrderService&quot;</pre><h3>Equivalent Java Configuration</h3><p>The above XML bean can be written using Java Configuration:</p><pre>@Configuration<br>public class AppConfig {<br>@Bean<br>    public OrderService getOrderService() {<br>        return new OrderService();<br>    }<br>}</pre><h3>Loading Spring XML Configuration</h3><p>Spring loads XML configuration through ApplicationContext.</p><pre>ApplicationContext context =<br>        new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);</pre><p>Once loaded, Spring creates and manages all beans defined in the XML file.</p><h3>Retrieving Beans from Spring Container</h3><h3>By Bean ID</h3><pre>OrderService orderService =<br>    (OrderService) context.getBean(&quot;orderService&quot;);</pre><p>Since getBean() returns Object, type casting is required.</p><h3>By Bean Type</h3><pre>OrderService orderService =<br>    context.getBean(OrderService.class);</pre><p>No casting required.</p><h3>Problem with Multiple Beans of Same Type</h3><p>Consider:</p><pre>&lt;bean id=&quot;os1&quot;<br>      class=&quot;com.gautam.OrderService&quot;/&gt;</pre><pre>&lt;bean id=&quot;os2&quot;<br>      class=&quot;com.gautam.OrderService&quot;/&gt;</pre><p>Now:</p><pre>context.getBean(OrderService.class);</pre><p>Spring doesn’t know which bean to return.</p><p>Result:</p><pre>NoUniqueBeanDefinitionException</pre><h3>Solution</h3><p>Specify bean id along with type.</p><pre>context.getBean(&quot;os1&quot;, OrderService.class);</pre><h3>Difference Between Bean id and name</h3><p>Example:</p><pre>&lt;bean id=&quot;os1&quot;<br>      name=&quot;orderBean,orderServiceBean&quot;<br>      class=&quot;com.gautam.OrderService&quot;/&gt;</pre><h3>id</h3><ul><li>Must be unique</li><li>Primary identifier</li></ul><h3>name</h3><ul><li>Used as aliases</li><li>Multiple aliases allowed</li></ul><p>All of these work:</p><pre>context.getBean(&quot;os1&quot;);<br>context.getBean(&quot;orderBean&quot;);<br>context.getBean(&quot;orderServiceBean&quot;);</pre><h3>Dependency Injection (DI)</h3><p>Dependency Injection means providing required dependencies from outside rather than creating them manually.</p><p>Example:</p><pre>public class OrderService {<br>private PaymentService paymentService;<br>}</pre><p>Instead of:</p><pre>paymentService = new PaymentService();</pre><p>Spring injects the dependency.</p><h3>Constructor Injection</h3><p>Suppose OrderService depends on PaymentService.</p><h3>Java Class</h3><pre>public class OrderService {<br>private PaymentService paymentService;<br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><h3>XML Configuration</h3><pre>&lt;bean id=&quot;paymentService&quot;<br>      class=&quot;com.gautam.PaymentService&quot;/&gt;<br>&lt;bean id=&quot;orderService&quot;<br>      class=&quot;com.gautam.OrderService&quot;&gt;<br>    &lt;constructor-arg ref=&quot;paymentService&quot;/&gt;<br>&lt;/bean&gt;</pre><p>Spring automatically injects PaymentService while creating OrderService.</p><h3>Constructor Injection with Primitive Values</h3><p>Class:</p><pre>public class PaymentService {<br>private String paymentType;<br>    public PaymentService(String paymentType) {<br>        this.paymentType = paymentType;<br>    }<br>}</pre><p>XML:</p><pre>&lt;bean id=&quot;paymentService&quot;<br>      class=&quot;com.gautam.PaymentService&quot;&gt;<br>&lt;constructor-arg value=&quot;UPI&quot;/&gt;<br>&lt;/bean&gt;</pre><p>Spring internally executes:</p><pre>new PaymentService(&quot;UPI&quot;);</pre><h3>Multiple Constructor Arguments</h3><p>Suppose:</p><pre>public PaymentService(<br>    String paymentType,<br>    int retryCount) {<br>}</pre><h3>Method 1</h3><pre>&lt;constructor-arg value=&quot;UPI&quot;/&gt;<br>&lt;constructor-arg value=&quot;3&quot;/&gt;</pre><h3>Method 2 (Using Index)</h3><pre>&lt;constructor-arg index=&quot;0&quot; value=&quot;UPI&quot;/&gt;<br>&lt;constructor-arg index=&quot;1&quot; value=&quot;3&quot;/&gt;</pre><h3>Method 3 (Using Name)</h3><pre>&lt;constructor-arg name=&quot;paymentType&quot; value=&quot;UPI&quot;/&gt;<br>&lt;constructor-arg name=&quot;retryCount&quot; value=&quot;3&quot;/&gt;</pre><p>This is the most readable approach.</p><h3>Setter Injection</h3><p>Class:</p><pre>public class OrderService {<br>private PaymentService paymentService;<br>    public void setPaymentService(<br>            PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>XML:</p><pre>&lt;bean id=&quot;paymentService&quot;<br>      class=&quot;com.gautam.PaymentService&quot;/&gt;<br>&lt;bean id=&quot;orderService&quot;<br>      class=&quot;com.gautam.OrderService&quot;&gt;<br>    &lt;property name=&quot;paymentService&quot;<br>              ref=&quot;paymentService&quot;/&gt;<br>&lt;/bean&gt;</pre><p>Spring automatically calls:</p><pre>orderService.setPaymentService(paymentService);</pre><h3>Constructor Injection vs Setter Injection</h3><p>Constructor InjectionSetter InjectionMandatory dependenciesOptional dependenciesObject fully initializedCan be modified laterPreferred approachUsed for optional fields</p><h3>Multiple Beans of Same Interface</h3><p>Consider:</p><pre>public interface PaymentService {<br>    void pay();<br>}</pre><p>Implementation 1:</p><pre>public class UpiPaymentService<br>        implements PaymentService {<br>}</pre><p>Implementation 2:</p><pre>public class CardPaymentService<br>        implements PaymentService {<br>}</pre><p>XML:</p><pre>&lt;bean id=&quot;upiPaymentService&quot;<br>      class=&quot;com.gautam.UpiPaymentService&quot;/&gt;<br>&lt;bean id=&quot;cardPaymentService&quot;<br>      class=&quot;com.gautam.CardPaymentService&quot;/&gt;</pre><p>Inject UPI:</p><pre>&lt;constructor-arg ref=&quot;upiPaymentService&quot;/&gt;</pre><p>Inject Card:</p><pre>&lt;constructor-arg ref=&quot;cardPaymentService&quot;/&gt;</pre><p>No ambiguity because Spring knows exactly which bean to inject.</p><h3>@Primary Equivalent in XML</h3><p>Annotation:</p><pre>@Primary</pre><p>XML:</p><pre>&lt;bean id=&quot;upiPaymentService&quot;<br>      class=&quot;com.gautam.UpiPaymentService&quot;<br>      primary=&quot;true&quot;/&gt;</pre><p>When multiple candidates exist, Spring prefers the bean marked as primary.</p><h3>Bean Scopes</h3><p>Scope defines how many instances Spring creates.</p><h3>Singleton Scope (Default)</h3><pre>&lt;bean id=&quot;userService&quot;<br>      class=&quot;com.gautam.UserService&quot;/&gt;</pre><p>Only one object exists.</p><pre>UserService a = context.getBean(UserService.class);<br>UserService b = context.getBean(UserService.class);</pre><p>Result:</p><pre>a == b</pre><p>Returns:</p><pre>true</pre><h3>Prototype Scope</h3><pre>&lt;bean id=&quot;userService&quot;<br>      class=&quot;com.gautam.UserService&quot;<br>      scope=&quot;prototype&quot;/&gt;</pre><p>Every request gets a new object.</p><pre>UserService a = context.getBean(UserService.class);<br>UserService b = context.getBean(UserService.class);</pre><p>Result:</p><pre>false</pre><h3>Injecting Collections</h3><p>Spring supports collection injection.</p><h3>List Injection</h3><p>Class:</p><pre>public class UserService {<br>private List&lt;String&gt; usernames;<br>    public UserService(List&lt;String&gt; usernames) {<br>        this.usernames = usernames;<br>    }<br>}</pre><p>XML:</p><pre>&lt;constructor-arg&gt;<br>&lt;list&gt;<br>        &lt;value&gt;Aditya&lt;/value&gt;<br>        &lt;value&gt;Rohit&lt;/value&gt;<br>        &lt;value&gt;Virat&lt;/value&gt;<br>    &lt;/list&gt;<br>&lt;/constructor-arg&gt;</pre><h3>Set Injection</h3><pre>&lt;set&gt;<br>    &lt;value&gt;A&lt;/value&gt;<br>    &lt;value&gt;B&lt;/value&gt;<br>&lt;/set&gt;</pre><p>Duplicates are automatically removed.</p><h3>Map Injection</h3><pre>&lt;map&gt;<br>&lt;entry key=&quot;101&quot;<br>           value=&quot;Aditya&quot;/&gt;<br>    &lt;entry key=&quot;102&quot;<br>           value=&quot;Rohit&quot;/&gt;<br>&lt;/map&gt;</pre><p>A key-value pair in a map is called an <strong>Entry</strong>.</p><h3>Spring Bean Lifecycle</h3><p>Spring follows a well-defined lifecycle.</p><pre>Constructor<br>↓<br>Dependency Injection<br>↓<br>init-method<br>↓<br>Bean Ready<br>↓<br>destroy-method</pre><h3>Example</h3><pre>public class User {<br>public User() {<br>        System.out.println(&quot;User created&quot;);<br>    }<br>    public void init() {<br>        System.out.println(&quot;Post Construct Phase&quot;);<br>    }<br>    public void cleanup() {<br>        System.out.println(&quot;Pre Destroy Phase&quot;);<br>    }<br>}</pre><p>XML:</p><pre>&lt;bean id=&quot;user&quot;<br>      class=&quot;com.gautam.User&quot;<br>      init-method=&quot;init&quot;<br>      destroy-method=&quot;cleanup&quot;/&gt;</pre><h3>Closing Context</h3><pre>ClassPathXmlApplicationContext context =<br>    new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);</pre><pre>context.close();</pre><p>Output:</p><pre>User created<br>Post Construct Phase<br>Pre Destroy Phase</pre><h3>Annotation Alternative</h3><p>Instead of XML:</p><pre>init-method=&quot;init&quot;<br>destroy-method=&quot;cleanup&quot;</pre><p>Use:</p><pre>@PostConstruct<br>public void init() {<br>}</pre><pre>@PreDestroy<br>public void cleanup() {<br>}</pre><h3>Prototype Bean Lifecycle Special Case</h3><p>For Prototype Scope:</p><pre>scope=&quot;prototype&quot;</pre><p>Spring:</p><ul><li>Creates the bean</li><li>Injects dependencies</li></ul><p>But Spring does <strong>not</strong> automatically invoke destroy methods.</p><p>Cleanup becomes the developer’s responsibility.</p><h3>Organizing Large XML Configurations</h3><p>As applications grow:</p><pre>beans.xml</pre><p>becomes difficult to maintain.</p><p>Split configurations:</p><pre>services.xml<br>repositories.xml<br>controllers.xml</pre><p>Then import them:</p><pre>&lt;beans&gt;<br>&lt;import resource=&quot;services.xml&quot;/&gt;<br>    &lt;import resource=&quot;repositories.xml&quot;/&gt;<br>    &lt;import resource=&quot;controllers.xml&quot;/&gt;<br>&lt;/beans&gt;</pre><p>This keeps configurations modular and maintainable.</p><h3>Key Takeaways</h3><p>✔ Spring IoC Container manages object creation and dependencies.</p><p>✔ Configuration metadata can be provided using XML or annotations.</p><p>✔ Beans can be retrieved using id, name, or type.</p><p>✔ Constructor Injection is generally preferred over Setter Injection.</p><p>✔ Multiple implementations can be resolved using explicit bean references or primary beans.</p><p>✔ Singleton is the default bean scope.</p><p>✔ Prototype creates a new object every request.</p><p>✔ Spring supports collection injection using List, Set, and Map.</p><p>✔ Bean lifecycle consists of creation, initialization, usage, and destruction phases.</p><p>✔ Large XML configurations can be organized using multiple files and the import tag.</p><h3>Conclusion</h3><p>Understanding XML-based Spring configuration provides deep insight into how Spring works internally. Even though modern Spring Boot applications rely heavily on annotations and auto-configuration, the concepts of IoC, Dependency Injection, Bean Scopes, Lifecycle Management, and Dependency Resolution remain exactly the same.</p><p>Mastering these fundamentals makes it significantly easier to understand Spring Boot, Spring Data JPA, Spring Security, Microservices, and advanced Spring ecosystem projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cf95343c82e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Spring Bean Lifecycle: A Complete Guide for Beginners]]></title>
            <link>https://medium.com/@suparngautam/understanding-the-spring-bean-lifecycle-a-complete-guide-for-beginners-20eb877ab4e6?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/20eb877ab4e6</guid>
            <category><![CDATA[spring-bean-lifecycle]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 17:21:54 GMT</pubDate>
            <atom:updated>2026-06-24T17:21:54.309Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Framework is one of the most powerful Java frameworks, and one of its core concepts is the <strong>Bean Lifecycle</strong>. Every Spring application revolves around beans managed by the <strong>IoC (Inversion of Control) Container</strong>.</p><p>Understanding how a bean is created, initialized, used, and destroyed is essential for every Spring Boot developer and is a frequently asked interview topic.</p><p>In this article, we’ll walk through the complete lifecycle of a Spring Bean step by step.</p><h3>What is a Spring Bean?</h3><p>A <strong>Bean</strong> is simply a Java object that is managed by the Spring Container.</p><p>For example:</p><pre>@Service<br>public class OrderService {<br>}</pre><p>When Spring starts, it creates and manages an instance of OrderService inside its IoC Container.</p><h3>What is the IoC Container?</h3><p>The <strong>IoC Container</strong> is responsible for:</p><ul><li>Creating beans</li><li>Managing bean lifecycle</li><li>Injecting dependencies</li><li>Destroying beans when the application shuts down</li></ul><p>A Spring application typically starts with:</p><pre>ApplicationContext context =<br>        new AnnotationConfigApplicationContext(AppConfig.class);</pre><p>At this point, the Spring IoC Container starts its work.</p><h3>Step 1: Container Startup</h3><p>The lifecycle begins when the Spring Container is created.</p><pre>ApplicationContext context =<br>        new AnnotationConfigApplicationContext(AppConfig.class);</pre><p>The container loads configuration classes and prepares itself to manage beans.</p><h3>Step 2: Reading Configuration</h3><p>Spring scans configuration classes and annotations such as:</p><pre>@Configuration<br>@ComponentScan<br>@Component<br>@Service<br>@Repository<br>@Controller<br>@Bean</pre><p>Example:</p><pre>@Configuration<br>@ComponentScan(&quot;com.example&quot;)<br>public class AppConfig {<br>}</pre><p>Spring analyzes these configurations to identify which classes should become beans.</p><h3>Step 3: Creating Bean Definitions</h3><p>Before creating actual objects, Spring first creates <strong>Bean Definitions</strong>.</p><p>A Bean Definition contains metadata about a bean:</p><p>PropertyExampleBean NameorderServiceBean ClassOrderServiceScopeSingletonLazy InitializationfalseDependenciesPaymentService</p><p>Think of a Bean Definition as a blueprint or recipe for creating the bean later.</p><p>This step is important because Spring wants complete information about all beans before creating them.</p><h3>Step 4: Bean Instantiation</h3><p>Once definitions are prepared, Spring creates bean objects.</p><pre>@Service<br>public class OrderService {<br>}</pre><p>Internally Spring performs:</p><pre>OrderService orderService =<br>        new OrderService();</pre><p>This is called <strong>Instantiation</strong>.</p><p>For singleton beans, Spring creates objects during application startup unless lazy loading is enabled.</p><h3>Step 5: Dependency Injection</h3><p>After object creation, Spring injects required dependencies.</p><p>Example:</p><pre>@Service<br>public class OrderService {<br>@Autowired<br>    private PaymentService paymentService;<br>}</pre><p>Spring first creates PaymentService and then injects it into OrderService.</p><p>At this stage, the bean object exists and all its required dependencies are available.</p><h3>Step 6: Aware Interfaces</h3><p>Sometimes a bean needs information about the Spring Container itself.</p><p>Spring provides special callback interfaces known as <strong>Aware Interfaces</strong>.</p><p>Examples include:</p><ul><li>BeanNameAware</li><li>BeanFactoryAware</li><li>ApplicationContextAware</li></ul><p>Example:</p><pre>public class OrderService<br>        implements BeanNameAware {<br>@Override<br>    public void setBeanName(String name) {<br>        System.out.println(name);<br>    }<br>}</pre><p>Spring automatically calls:</p><pre>setBeanName()</pre><p>and provides the bean’s name.</p><p>These callbacks are mainly used for framework-level programming, debugging, and logging rather than business logic.</p><h3>Step 7: Initialization Phase</h3><p>After dependency injection is complete, Spring performs bean initialization.</p><p>There are three common approaches.</p><h3>1. Using @PostConstruct (Most Popular)</h3><pre>@PostConstruct<br>public void init() {<br>    System.out.println(&quot;Bean initialized&quot;);<br>}</pre><p>This method executes automatically after dependency injection.</p><h3>Why not use the constructor?</h3><p>The constructor runs before dependency injection.</p><pre>public OrderService() {<br>}</pre><p>At constructor time, dependencies may not yet be available.</p><p>However, when @PostConstruct executes, all dependencies have already been injected.</p><p>This makes it the preferred location for initialization logic.</p><h3>2. Using InitializingBean</h3><p>Spring provides the InitializingBean interface.</p><pre>public class OrderService<br>        implements InitializingBean {<br>@Override<br>    public void afterPropertiesSet() {<br>        System.out.println(&quot;Initialized&quot;);<br>    }<br>}</pre><p>Spring automatically calls:</p><pre>afterPropertiesSet()</pre><p>after dependency injection.</p><h3>3. Using initMethod</h3><p>You can define an initialization method inside configuration.</p><pre>@Bean(initMethod = &quot;start&quot;)<br>public OrderService orderService() {<br>    return new OrderService();<br>}</pre><pre>public void start() {<br>    System.out.println(&quot;Started&quot;);<br>}</pre><p>Spring invokes the start() method during initialization.</p><h3>Step 8: Bean Ready for Use</h3><p>At this point:</p><ul><li>Object has been created</li><li>Dependencies have been injected</li><li>Initialization methods have executed</li></ul><p>The bean is now fully ready for use.</p><pre>OrderService service =<br>        context.getBean(OrderService.class);</pre><h3>Destruction Phase</h3><p>When the application shuts down:</p><pre>context.close();</pre><p>Spring begins destroying managed beans.</p><p>Before destroying a bean, Spring provides several destruction callbacks.</p><h3>Step 9: Destruction Callbacks</h3><p>Just like initialization, there are three ways to perform cleanup operations.</p><h3>1. Using @PreDestroy (Recommended)</h3><pre>@PreDestroy<br>public void cleanup() {<br>    System.out.println(&quot;Cleaning resources&quot;);<br>}</pre><p>This is the most commonly used approach.</p><h3>2. Using DisposableBean</h3><pre>public class OrderService<br>        implements DisposableBean {<br>@Override<br>    public void destroy() {<br>        System.out.println(&quot;Destroyed&quot;);<br>    }<br>}</pre><p>Spring invokes:</p><pre>destroy()</pre><p>before removing the bean.</p><h3>3. Using destroyMethod</h3><pre>@Bean(destroyMethod = &quot;stop&quot;)<br>public OrderService orderService() {<br>    return new OrderService();<br>}</pre><pre>public void stop() {<br>    System.out.println(&quot;Stopping resources&quot;);<br>}</pre><p>Spring automatically executes stop() during shutdown.</p><h3>Step 10: Bean Destruction</h3><p>Finally, Spring removes the bean from the container.</p><p>This stage is used to release resources such as:</p><ul><li>Database connections</li><li>Thread pools</li><li>File streams</li><li>Network sockets</li><li>Cache resources</li></ul><p>The bean lifecycle is now complete.</p><h3>Complete Lifecycle Flow</h3><pre>1. Container Starts<br>2. Read Configuration<br>3. Create Bean Definition<br>4. Instantiate Bean<br>5. Inject Dependencies<br>6. Execute Aware Interfaces<br>7. @PostConstruct<br>8. afterPropertiesSet()<br>9. initMethod()<br><br>Bean Ready To Use<br>10. @PreDestroy<br>11. destroy()<br>12. destroyMethod()<br>Bean Destroyed</pre><h3>Singleton vs Prototype Beans</h3><p>Understanding lifecycle behavior becomes even more important when dealing with bean scopes.</p><h3>Singleton Scope</h3><pre>@Scope(&quot;singleton&quot;)</pre><p>Characteristics:</p><ul><li>One object per Spring Container</li><li>Default scope</li><li>Spring manages the complete lifecycle</li><li>Initialization and destruction callbacks work normally</li></ul><h3>Prototype Scope</h3><pre>@Scope(&quot;prototype&quot;)</pre><p>Characteristics:</p><ul><li>New object created every time the bean is requested</li></ul><p>Example:</p><pre>context.getBean(User.class);<br>context.getBean(User.class);</pre><p>This creates two different objects.</p><h3>Important Difference</h3><p>For Prototype Beans, Spring performs:</p><p>✅ Object Creation</p><p>✅ Dependency Injection</p><p>✅ Initialization Callbacks</p><p>But Spring does NOT perform:</p><p>❌ Destruction Callbacks</p><p>Once a prototype bean is handed over to the application, Spring stops managing it.</p><p>The object is later cleaned up by Java’s Garbage Collector.</p><h3>Why is @PostConstruct Preferred Over Constructors?</h3><p>This is a very common interview question.</p><h3>Constructor</h3><pre>public OrderService() {<br>}</pre><p>Runs during object creation.</p><p>Dependencies may not yet be available.</p><h3>@PostConstruct</h3><pre>@PostConstruct<br>public void init() {<br>}</pre><p>Runs after dependency injection.</p><p>All dependencies are ready to use.</p><p>Therefore, initialization logic should generally be placed inside @PostConstruct rather than constructors.</p><h3>Conclusion</h3><p>The Spring Bean Lifecycle is a fundamental concept that explains how Spring manages objects from creation to destruction. Understanding each phase helps developers write cleaner applications, manage resources effectively, and debug dependency-related issues more efficiently.</p><p>To summarize:</p><ul><li>Spring first creates Bean Definitions.</li><li>Beans are instantiated and dependencies injected.</li><li>Initialization callbacks are executed.</li><li>Beans become available for use.</li><li>Destruction callbacks run when the container shuts down.</li><li>Prototype beans are not fully managed during destruction.</li></ul><p>Mastering the Bean Lifecycle will make you more confident in Spring Boot development and help you answer some of the most frequently asked interview questions with ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20eb877ab4e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spring IoC Container, Bean Scopes, Lazy Initialization, and Circular Dependency]]></title>
            <link>https://medium.com/@suparngautam/understanding-spring-ioc-container-bean-scopes-lazy-initialization-and-circular-dependency-3a621be9d024?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a621be9d024</guid>
            <category><![CDATA[circular-dependencies]]></category>
            <category><![CDATA[lazy-annoation]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 14:43:50 GMT</pubDate>
            <atom:updated>2026-06-23T14:43:50.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>One of the most important concepts in Spring Framework is the <strong>IoC (Inversion of Control) Container</strong>. Spring manages the lifecycle of objects, injects dependencies, and controls bean creation. Understanding how Spring creates and manages beans is essential for becoming proficient in Spring Boot development.</p><p>In this article, we’ll explore:</p><ul><li>Spring IoC Container</li><li>Dependency Injection</li><li>Circular Dependency</li><li>Bean Scopes</li><li>Singleton vs Prototype</li><li>Lazy vs Eager Initialization</li><li>The @Lazy Annotation</li></ul><h3>What is the Spring IoC Container?</h3><p>IoC stands for <strong>Inversion of Control</strong>.</p><p>Traditionally, developers create objects manually:</p><pre>PaymentService paymentService = new PaymentService();<br>OrderService orderService = new OrderService(paymentService);</pre><p>In Spring, the framework takes responsibility for creating and managing objects.</p><p>Consider the following classes:</p><pre>@Service<br>public class PaymentService {<br>}</pre><pre>@Service<br>public class OrderService {<br>private final PaymentService paymentService;<br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>When the application starts, Spring:</p><ol><li>Creates the PaymentService bean.</li><li>Creates the OrderService bean.</li><li>Injects PaymentService into OrderService.</li><li>Stores both beans in the IoC Container.</li></ol><p>This process is called <strong>Dependency Injection (DI)</strong>.</p><h3>Dependency Injection</h3><p>Dependency Injection means providing required dependencies from outside instead of creating them inside the class.</p><p>Bad Practice:</p><pre>public class OrderService {<br>private PaymentService paymentService = new PaymentService();<br>}</pre><p>Good Practice:</p><pre>public class OrderService {<br>private final PaymentService paymentService;<br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>Benefits:</p><ul><li>Loose coupling</li><li>Easier testing</li><li>Better maintainability</li><li>Improved scalability</li></ul><h3>Circular Dependency</h3><p>A circular dependency occurs when two classes depend on each other.</p><p>Example:</p><pre>@Service<br>public class OrderService {<br>private final PaymentService paymentService;<br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><pre>@Service<br>public class PaymentService {<br>private final OrderService orderService;<br>    public PaymentService(OrderService orderService) {<br>        this.orderService = orderService;<br>    }<br>}</pre><p>Dependency graph:</p><pre>OrderService -&gt; PaymentService<br>PaymentService -&gt; OrderService</pre><p>Now Spring tries:</p><pre>Create OrderService<br>    Needs PaymentService</pre><pre>Create PaymentService<br>    Needs OrderService</pre><pre>Create OrderService<br>    Needs PaymentService</pre><p>This becomes an infinite loop.</p><h3>Why Circular Dependency is Bad</h3><p>Circular dependency creates:</p><ul><li>Tight coupling</li><li>Difficult testing</li><li>Complex maintenance</li><li>Violation of SOLID principles</li></ul><p>Spring Boot disables circular references by default:</p><pre>spring.main.allow-circular-references=false</pre><p>The recommended solution is to redesign the classes and remove the circular dependency.</p><p>Instead of:</p><pre>A -&gt; B<br>B -&gt; A</pre><p>Use:</p><pre>A -&gt; C<br>B -&gt; C</pre><p>where C contains the shared functionality.</p><h3>Bean Scopes in Spring</h3><p>A Bean Scope determines how many instances of a bean Spring should create.</p><p>Spring supports multiple scopes:</p><ol><li>Singleton</li><li>Prototype</li><li>Request</li><li>Session</li><li>Application</li></ol><h3>Singleton Scope (Default)</h3><p>Singleton is the default scope in Spring.</p><pre>@Service<br>public class OrderService {<br>}</pre><p>Equivalent to:</p><pre>@Service<br>@Scope(&quot;singleton&quot;)<br>public class OrderService {<br>}</pre><p>When requested multiple times:</p><pre>OrderService bean1 = context.getBean(OrderService.class);<br>OrderService bean2 = context.getBean(OrderService.class);</pre><p>Result:</p><pre>bean1 == bean2 // true</pre><p>Both variables reference the same object.</p><h3>Important Clarification About Singleton</h3><p>Many developers think:</p><blockquote><em>Singleton means one object per class.</em></blockquote><p>This is not completely correct in Spring.</p><p>Consider:</p><pre>@Bean<br>public OrderService os1() {<br>    return new OrderService();<br>}</pre><pre>@Bean<br>public OrderService os2() {<br>    return new OrderService();<br>}</pre><p>Spring creates:</p><pre>os1 -&gt; OrderService Object #1<br>os2 -&gt; OrderService Object #2</pre><p>Therefore:</p><p><strong>Singleton means one object per bean definition, not one object per class.</strong></p><h3>Prototype Scope</h3><p>Prototype scope creates a new object every time the bean is requested.</p><pre>@Service<br>@Scope(&quot;prototype&quot;)<br>public class OrderService {<br>}</pre><p>Example:</p><pre>OrderService bean1 = context.getBean(OrderService.class);<br>OrderService bean2 = context.getBean(OrderService.class);</pre><p>Result:</p><pre>bean1 == bean2 // false</pre><p>Each request receives a fresh object.</p><h3>When Should You Use Singleton?</h3><p>Singleton is ideal for stateless services.</p><p>Example:</p><pre>@Service<br>public class PaymentService {<br>public void processPayment() {<br>        // business logic<br>    }<br>}</pre><p>Characteristics:</p><ul><li>No mutable state</li><li>Thread-safe</li><li>Shared across the application</li></ul><p>Most Spring services should be Singleton.</p><h3>When Should You Use Prototype?</h3><p>Prototype is useful when the bean contains state.</p><p>Example:</p><pre>@Component<br>@Scope(&quot;prototype&quot;)<br>public class ShoppingCart {<br>private List&lt;Item&gt; items = new ArrayList&lt;&gt;();<br>}</pre><p>Each user should receive a separate cart instance.</p><p>Characteristics:</p><ul><li>Stateful objects</li><li>User-specific data</li><li>Temporary objects</li></ul><h3>Request Scope</h3><p>One bean instance per HTTP request.</p><pre>@Scope(value = WebApplicationContext.SCOPE_REQUEST)</pre><p>Example:</p><pre>Request 1 -&gt; Bean A<br>Request 2 -&gt; Bean B</pre><p>Different requests receive different bean instances.</p><h3>Session Scope</h3><p>One bean instance per user session.</p><pre>@Scope(value = WebApplicationContext.SCOPE_SESSION)</pre><p>Example:</p><pre>User A Session -&gt; Cart A<br>User B Session -&gt; Cart B</pre><p>Each user maintains their own bean instance.</p><h3>Application Scope</h3><p>One bean instance for the entire web application.</p><pre>@Scope(value = WebApplicationContext.SCOPE_APPLICATION)</pre><p>The bean remains available until the application shuts down.</p><h3>Bean Initialization</h3><p>Spring supports two types of bean initialization:</p><ol><li>Eager Initialization</li><li>Lazy Initialization</li></ol><h3>Eager Initialization</h3><p>By default, Singleton beans are eagerly initialized.</p><pre>@Service<br>public class OrderService {<br>}</pre><p>Spring creates the bean during application startup.</p><p>Benefits:</p><ul><li>Fail-fast behavior</li><li>Startup validation</li><li>Immediate availability</li></ul><p>If configuration problems exist, they are detected when the application starts.</p><h3>Lazy Initialization</h3><p>Lazy initialization delays bean creation until the bean is actually required.</p><pre>@Lazy<br>@Service<br>public class OrderService {<br>}</pre><p>Now Spring creates the object only when it is first accessed.</p><p>Example:</p><pre>context.getBean(OrderService.class);</pre><p>At this point, the bean gets created.</p><p>Benefits:</p><ul><li>Faster startup</li><li>Lower memory usage</li><li>Useful for expensive objects</li></ul><h3>Why Prototype Beans Behave Lazily</h3><p>Prototype beans are not created during application startup.</p><p>Instead:</p><pre>context.getBean(MyPrototypeBean.class);</pre><p>creates a new instance every time.</p><p>Because Spring does not create prototype beans at startup, they naturally behave like lazy beans.</p><h3>Understanding @Lazy on Dependencies</h3><p>Consider:</p><pre>@Service<br>public class OrderService {<br>private final PaymentService paymentService;<br>    public OrderService(<br>            @Lazy PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>Spring does not inject the real PaymentService immediately.</p><p>Instead, Spring injects a proxy object.</p><h3>What is a Proxy?</h3><p>A proxy acts as a placeholder.</p><pre>OrderService<br>      |<br>      v<br>Proxy Object<br>      |<br>      v<br>PaymentService</pre><p>When OrderService calls a method:</p><pre>paymentService.processPayment();</pre><p>The proxy:</p><ol><li>Creates the real PaymentService.</li><li>Delegates the method call.</li><li>Returns the result.</li></ol><p>This is how Spring implements lazy dependency injection.</p><h3>Can @Lazy Solve Circular Dependency?</h3><p>Example:</p><pre>@Service<br>public class A {<br>public A(@Lazy B b) {<br>    }<br>}</pre><pre>@Service<br>public class B {<br>public B(A a) {<br>    }<br>}</pre><p>Because Spring injects a proxy, the application may start successfully.</p><p>However, this should not be considered the ideal solution.</p><p>Recommended approach:</p><ul><li>Redesign the architecture.</li><li>Remove the circular dependency.</li><li>Use @Lazy only when necessary.</li></ul><h3>Best Practices</h3><p>✅ Use constructor injection.</p><p>✅ Keep services stateless.</p><p>✅ Prefer Singleton scope for services.</p><p>✅ Use Prototype only for stateful objects.</p><p>✅ Avoid circular dependencies.</p><p>✅ Use @Lazy sparingly.</p><p>✅ Follow SOLID principles.</p><h3>Conclusion</h3><p>Spring’s IoC Container is responsible for creating, managing, and wiring beans together. Understanding bean scopes, dependency injection, lazy initialization, and circular dependencies helps developers write cleaner, more maintainable applications.</p><p>As a rule of thumb:</p><ul><li>Singleton for stateless services.</li><li>Prototype for stateful objects.</li><li>Avoid circular dependencies.</li><li>Prefer constructor injection.</li><li>Use @Lazy only when genuinely required.</li></ul><p>Mastering these concepts will make Spring Boot development significantly easier and help you design scalable enterprise applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a621be9d024" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot Dependency Injection Explained: IoC, Beans, Autowiring, @Primary, and @Qualifier]]></title>
            <link>https://medium.com/@suparngautam/spring-boot-dependency-injection-explained-ioc-beans-autowiring-primary-and-qualifier-ac120ca83e30?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac120ca83e30</guid>
            <category><![CDATA[types-of-autowiring]]></category>
            <category><![CDATA[spring-ioc]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 16:45:30 GMT</pubDate>
            <atom:updated>2026-06-20T16:45:30.956Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve just started learning Spring Boot, you’ve probably heard terms like <strong>IoC Container</strong>, <strong>Bean</strong>, <strong>Autowiring</strong>, <strong>Dependency Injection</strong>, <strong>@Primary</strong>, and <strong>@Qualifier</strong>. At first, these concepts can feel confusing because they are all closely related.</p><p>In this article, we’ll break down these concepts with simple examples and understand how Spring manages objects behind the scenes.</p><h3>What Problem Does Spring Solve?</h3><p>Imagine you’re building an e-commerce application.</p><pre>public class PaymentService {<br>}</pre><pre>public class OrderService {<br>private PaymentService paymentService =<br>            new PaymentService();<br>}</pre><p>Here, OrderService creates its own dependency using the new keyword.</p><p>This approach works for small applications, but as projects grow:</p><ul><li>Classes become tightly coupled.</li><li>Testing becomes difficult.</li><li>Managing object creation becomes complex.</li></ul><p>Spring solves this problem using <strong>Inversion of Control (IoC)</strong> and <strong>Dependency Injection (DI)</strong>.</p><h3>What is Inversion of Control (IoC)?</h3><p>Traditionally, developers create objects manually.</p><pre>PaymentService paymentService =<br>        new PaymentService();</pre><pre>OrderService orderService =<br>        new OrderService(paymentService);</pre><p>With Spring, object creation responsibility is transferred to the framework.</p><p>Instead of creating objects yourself, Spring creates and manages them.</p><p>This concept is called <strong>Inversion of Control (IoC)</strong>.</p><blockquote><em>Control of object creation moves from the programmer to the Spring Framework.</em></blockquote><h3>What is the IoC Container?</h3><p>The <strong>IoC Container</strong> is the core component of Spring responsible for:</p><ul><li>Creating objects</li><li>Managing object lifecycle</li><li>Injecting dependencies</li><li>Storing and providing beans</li></ul><p>Think of it as a warehouse where Spring keeps all application objects.</p><pre>Spring IoC Container</pre><pre>-------------------------<br>PaymentService Bean<br>OrderService Bean<br>UserService Bean<br>-------------------------</pre><p>Whenever an object is needed, Spring provides it from the container.</p><h3>What is a Bean?</h3><p>A <strong>Bean</strong> is simply an object managed by the Spring Container.</p><p>Example:</p><pre>@Component<br>public class User {<br>}</pre><p>Spring automatically creates:</p><pre>User user = new User();</pre><p>and stores it inside the IoC Container.</p><p>This managed object is called a <strong>Spring Bean</strong>.</p><h3>Bean Stereotype Annotations</h3><p>Spring provides several annotations to register beans.</p><h3>@Component</h3><pre>@Component<br>public class User {<br>}</pre><p>Generic bean annotation.</p><h3>@Service</h3><pre>@Service<br>public class PaymentService {<br>}</pre><p>Used for business logic classes.</p><h3>@Repository</h3><pre>@Repository<br>public class UserRepository {<br>}</pre><p>Used for database access classes.</p><h3>@Controller</h3><pre>@Controller<br>public class UserController {<br>}</pre><p>Used for handling web requests.</p><h3>How Does Spring Find These Beans?</h3><p>Spring uses <strong>Component Scanning</strong>.</p><p>Consider the following structure:</p><pre>com.example</pre><pre>├── Application<br>├── service<br>│     └── PaymentService<br>├── repository<br>│     └── UserRepository<br>└── controller<br>      └── UserController</pre><pre>@SpringBootApplication<br>public class Application {<br>}</pre><p>When the application starts, Spring scans:</p><pre>com.example<br>com.example.service<br>com.example.repository<br>com.example.controller</pre><p>and automatically registers annotated classes as beans.</p><h3>What is Dependency Injection?</h3><p>Suppose OrderService needs PaymentService.</p><p>Without Spring:</p><pre>PaymentService paymentService =<br>        new PaymentService();</pre><p>With Spring:</p><pre>@Service<br>public class OrderService {<br>private final PaymentService paymentService;<br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>Spring automatically injects the required dependency.</p><p>This process is called <strong>Dependency Injection (DI)</strong>.</p><h3>Types of Dependency Injection</h3><p>Spring supports three types of dependency injection.</p><h3>1. Constructor Injection (Recommended)</h3><pre>@Service<br>public class OrderService {<br>private final PaymentService paymentService;<br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><h3>Advantages</h3><ul><li>Dependency available during object creation</li><li>Supports final fields</li><li>Easy unit testing</li><li>Promotes immutability</li><li>Recommended by Spring team</li></ul><h3>2. Setter Injection</h3><pre>@Service<br>public class OrderService {<br>private PaymentService paymentService;<br>    @Autowired<br>    public void setPaymentService(<br>            PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>Flow:</p><ol><li>Spring creates OrderService.</li><li>Spring calls setter method.</li><li>Dependency gets injected.</li></ol><p>Useful when dependencies are optional.</p><h3>3. Field Injection</h3><pre>@Service<br>public class OrderService {<br>@Autowired<br>    private PaymentService paymentService;<br>}</pre><p>Although this works, it is generally discouraged.</p><h3>Problems</h3><ul><li>Difficult to unit test</li><li>Hidden dependencies</li><li>Cannot use final fields</li><li>Uses reflection internally</li></ul><p>For modern Spring Boot projects, constructor injection is preferred.</p><h3>Why Constructor Injection is the Best Choice?</h3><h3>Supports Immutability</h3><pre>private final PaymentService paymentService;</pre><p>The dependency cannot be changed after object creation.</p><h3>Easier Unit Testing</h3><pre>PaymentService mock =<br>        new PaymentService();</pre><pre>OrderService orderService =<br>        new OrderService(mock);</pre><p>No Spring context required.</p><h3>Dependencies are Explicit</h3><p>Looking at the constructor immediately tells us what the class needs.</p><pre>public OrderService(<br>        PaymentService paymentService)</pre><p>No hidden dependencies.</p><h3>Do We Need @Autowired on Constructors?</h3><p>If a class has only one constructor:</p><pre>@Service<br>public class OrderService {<br>private final PaymentService paymentService;<br>    public OrderService(<br>            PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>Spring automatically performs constructor injection.</p><p>No need for @Autowired.</p><h3>Why is This Incorrect?</h3><p>Many beginners write:</p><pre>@Autowired<br>private final PaymentService paymentService;</pre><p>This is incorrect.</p><p>Reason:</p><p>Field injection happens after object creation, while a final field must be initialized during construction.</p><p>The correct approach is:</p><pre>private final PaymentService paymentService;<br>public OrderService(<br>        PaymentService paymentService) {<br>    this.paymentService = paymentService;<br>}</pre><h3>What Happens When Multiple Beans Exist?</h3><p>Suppose we have:</p><pre>@Component<br>public class GPayPaymentService<br>        implements PaymentService {<br>}</pre><pre>@Component<br>public class UpiPaymentService<br>        implements PaymentService {<br>}</pre><p>Now Spring finds two implementations.</p><pre>private final PaymentService paymentService;</pre><p>Spring doesn’t know which bean to inject and throws:</p><pre>NoUniqueBeanDefinitionException</pre><h3>Solving Multiple Bean Conflicts Using @Primary</h3><pre>@Component<br>@Primary<br>public class GPayPaymentService<br>        implements PaymentService {<br>}</pre><p>Now Spring injects this bean by default.</p><h3>Solving Multiple Bean Conflicts Using @Qualifier</h3><pre>@Component(&quot;gpay&quot;)<br>public class GPayPaymentService<br>        implements PaymentService {<br>}</pre><pre>@Component(&quot;upi&quot;)<br>public class UpiPaymentService<br>        implements PaymentService {<br>}</pre><p>Inject a specific implementation:</p><pre>public OrderService(<br>        @Qualifier(&quot;upi&quot;)<br>        PaymentService paymentService) {<br>          this.paymentService = paymentService;<br>        }</pre><p>Spring now injects the UPI implementation.</p><h3>Spring Bean Lifecycle (Simplified)</h3><p>When the application starts:</p><h3>Step 1</h3><p>Spring Boot starts.</p><h3>Step 2</h3><p>Component scanning occurs.</p><h3>Step 3</h3><p>Bean definitions are created.</p><h3>Step 4</h3><p>Beans are instantiated.</p><h3>Step 5</h3><p>Dependencies are injected.</p><h3>Step 6</h3><p>Beans become ready for use.</p><h3>Key Takeaways</h3><ul><li><strong>IoC</strong> means Spring controls object creation.</li><li><strong>IoC Container</strong> creates and manages beans.</li><li><strong>Bean</strong> is an object managed by Spring.</li><li><strong>Component Scanning</strong> finds classes annotated with Spring stereotypes.</li><li><strong>Dependency Injection</strong> allows Spring to provide dependencies automatically.</li><li><strong>Constructor Injection</strong> is the recommended approach.</li><li><strong>Setter Injection</strong> is useful for optional dependencies.</li><li><strong>Field Injection</strong> should generally be avoided.</li><li><strong>@Primary</strong> resolves conflicts by choosing a default bean.</li><li><strong>@Qualifier</strong> allows selecting a specific bean.</li><li>If there is only one constructor, <strong>@Autowired is not required</strong>.</li></ul><p>Understanding these concepts is essential because they form the foundation of Spring Boot. Once you’re comfortable with IoC and Dependency Injection, advanced topics like Spring MVC, Spring Data JPA, Security, and Microservices become much easier to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac120ca83e30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Dependency Injection (DI), Inversion of Control (IoC), and the Spring IoC Container]]></title>
            <link>https://medium.com/@suparngautam/understanding-dependency-injection-di-inversion-of-control-ioc-and-the-spring-ioc-container-b56de1968ab7?source=rss-9ab5d1e79fb3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b56de1968ab7</guid>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[java-dependency-injection]]></category>
            <dc:creator><![CDATA[Suparngautam]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 03:39:32 GMT</pubDate>
            <atom:updated>2026-06-19T03:39:32.323Z</atom:updated>
            <content:encoded><![CDATA[<p>When learning Spring Boot, one of the first modules you’ll encounter is <strong>Spring Core</strong>. While Spring Boot provides many powerful features, everything is built on the foundation of Spring Core.</p><p>The two most important concepts in Spring Core are:</p><ul><li>Dependency Injection (DI)</li><li>Inversion of Control (IoC)</li></ul><p>If you understand these concepts well, you’ll find it much easier to learn Spring MVC, Spring Data JPA, Spring Security, and other Spring ecosystem projects.</p><p>In this article, we’ll understand Dependency Injection and Inversion of Control from scratch with practical examples.</p><h3>Why Do We Need Dependency Injection?</h3><p>Many beginners ask:</p><blockquote><em>“We already have Object-Oriented Programming (OOP). Why do we need Dependency Injection?”</em></blockquote><p>The answer lies in <strong>maintainability, flexibility, and testability</strong>.</p><p>A widely accepted software engineering principle states:</p><blockquote><em>Program to interfaces rather than concrete implementations.</em></blockquote><p>The problem is not creating objects. The problem is deciding <strong>where and how objects are created</strong>.</p><p>When a class creates its own dependencies, it becomes tightly coupled with them.</p><p>Let’s understand this with an example.</p><h3>Traditional Approach: Tight Coupling</h3><p>Consider an application that sends emails when an order is placed.</p><pre>public class EmailService {<br>public void sendEmail() {<br>        System.out.println(&quot;Email Sent&quot;);<br>    }<br>}</pre><p>Now let’s create an OrderService.</p><pre>public class OrderService {<br>private EmailService emailService = new EmailService();<br>    public void placeOrder() {<br>        emailService.sendEmail();<br>        System.out.println(&quot;Order Placed&quot;);<br>    }<br>}</pre><p>At first glance, this code seems fine.</p><p>However, there is a hidden issue.</p><p>OrderService is directly creating an object of EmailService.</p><pre>new EmailService();</pre><p>This creates a strong dependency between the two classes.</p><h3>Problems with This Approach</h3><ul><li>Tight coupling</li><li>Difficult to replace implementations</li><li>Harder to test</li><li>Reduced flexibility</li><li>Violates the Dependency Inversion Principle</li></ul><p>Suppose tomorrow you want to replace EmailService with SMSService.</p><p>You would need to modify OrderService.</p><p>This indicates poor design.</p><h3>Dependency Injection (DI)</h3><p>Dependency Injection solves this problem.</p><p>The idea is simple:</p><blockquote><em>Don’t create your own dependencies. Receive them from an external source.</em></blockquote><p>Instead of creating EmailService inside OrderService, we inject it from outside.</p><pre>public class OrderService {</pre><pre>    private EmailService emailService;</pre><pre>    public OrderService(EmailService emailService) {<br>        this.emailService = emailService;<br>    }<br>}</pre><p>Now OrderService no longer creates EmailService.</p><p>Someone else provides it.</p><p>This process is called <strong>Dependency Injection</strong>.</p><h3>Real-World Analogy</h3><p>Imagine buying a car.</p><h3>Without Dependency Injection</h3><p>The car manufactures its own engine.</p><pre>Car -&gt; Creates Engine</pre><p>If you want a different engine, you must redesign the car.</p><h3>With Dependency Injection</h3><p>The engine is supplied to the car.</p><pre>Engine -&gt; Provided -&gt; Car</pre><p>The car simply uses the engine.</p><p>It doesn’t care who created it.</p><p>This is exactly how Dependency Injection works.</p><h3>Benefits of Dependency Injection</h3><h3>1. Loose Coupling</h3><p>Classes become independent of concrete implementations.</p><p>Instead of:</p><pre>EmailService emailService;</pre><p>We can depend on an interface:</p><pre>NotificationService notificationService;</pre><h3>2. Better Testability</h3><p>Testing becomes easier because we can inject mock objects.</p><pre>OrderService service =<br>    new OrderService(new MockNotificationService());</pre><p>No need to send real emails during testing.</p><h3>3. Easy Maintenance</h3><p>Implementations can be changed without modifying business logic.</p><p>For example:</p><pre>EmailService</pre><p>can easily become</p><pre>SMSService</pre><p>or</p><pre>WhatsAppService</pre><p>without affecting OrderService.</p><h3>4. Better Reusability</h3><p>Components become reusable because they are not tightly coupled.</p><h3>Types of Dependency Injection</h3><p>Spring supports three types of dependency injection.</p><h3>1. Constructor Injection (Recommended)</h3><pre>@Service<br>public class OrderService {<br>private final EmailService emailService;<br>    public OrderService(EmailService emailService) {<br>        this.emailService = emailService;<br>    }<br>}</pre><h4>Advantages</h4><ul><li>Mandatory dependencies</li><li>Better testability</li><li>Immutable objects</li><li>Recommended by Spring</li></ul><p>This is the most preferred approach.</p><h3>2. Setter Injection</h3><pre>@Service<br>public class OrderService {<br>private EmailService emailService;<br>    @Autowired<br>    public void setEmailService(<br>            EmailService emailService) {<br>        this.emailService = emailService;<br>    }<br>}</pre><p>Useful when dependencies are optional.</p><h3>3. Field Injection</h3><pre>@Service<br>public class OrderService {<br>@Autowired<br>    private EmailService emailService;<br>}</pre><p>Although commonly seen in tutorials, field injection is generally discouraged because:</p><ul><li>Hidden dependencies</li><li>Difficult unit testing</li><li>Less maintainable</li></ul><h3>What Is Inversion of Control (IoC)?</h3><p>Before understanding IoC, let’s understand who currently controls object creation.</p><p>In traditional Java applications:</p><pre>OrderService orderService =<br>        new OrderService();</pre><p>The developer controls object creation.</p><pre>Developer<br>     |<br>Creates Objects</pre><p>This means the application controls everything.</p><h3>With IoC</h3><p>The framework takes over object creation and management.</p><pre>Spring Framework<br>        |<br>Creates Objects</pre><p>Control is transferred from the application code to the framework.</p><p>This transfer of control is called:</p><h3>Inversion of Control (IoC)</h3><h3>Understanding IoC with an Example</h3><h3>Before IoC</h3><pre>OrderService<br>      |<br>Creates<br>      |<br>EmailService</pre><p>OrderService is responsible for creating its dependency.</p><h3>After IoC</h3><pre>Spring Container<br>       |<br>Creates EmailService<br>       |<br>Injects Into<br>       |<br>OrderService</pre><p>Now Spring manages object creation and wiring.</p><p>This is Inversion of Control.</p><h3>Relationship Between IoC and DI</h3><p>Many developers confuse these terms.</p><p>The simplest way to remember them is:</p><p>IoCDIPrincipleTechniqueGoalImplementationTransfers controlInjects dependenciesHigh-level conceptPractical solution</p><p>Think of it like this:</p><pre>IoC = What we want</pre><pre>DI = How we achieve it</pre><p>Or:</p><pre>IoC is the idea<br>DI is the implementation</pre><h3>Spring IoC Container</h3><p>Spring provides something called the <strong>IoC Container</strong>.</p><p>The container is responsible for:</p><h3>Creating Objects</h3><p>Instead of writing:</p><pre>new EmailService();</pre><p>Spring creates the object.</p><h3>Managing Objects</h3><p>The container manages the complete lifecycle of objects.</p><p>It decides:</p><ul><li>When objects are created</li><li>How long they live</li><li>When they are destroyed</li></ul><h3>Connecting Objects</h3><p>The container automatically injects dependencies.</p><pre>EmailService<br>      |<br>Injected Into<br>      |<br>OrderService</pre><p>This process happens automatically.</p><h3>What Are Beans?</h3><p>In normal Java:</p><pre>EmailService emailService =<br>        new EmailService();</pre><p>It is simply an object.</p><p>In Spring:</p><pre>@Service<br>public class EmailService {<br>}</pre><p>The object is managed by Spring.</p><p>Such managed objects are called:</p><h3>Beans</h3><h3>Definition</h3><p>A Bean is an object that is created, managed, and maintained by the Spring IoC Container.</p><h3>How Spring Creates Beans</h3><p>Spring scans classes containing annotations such as:</p><pre>@Component</pre><pre>@Service</pre><pre>@Repository</pre><pre>@Controller</pre><p>When the application starts:</p><ol><li>Spring scans the project.</li><li>Finds these annotations.</li><li>Creates objects.</li><li>Stores them inside the IoC Container.</li><li>Injects them wherever required.</li></ol><h3>Main Method vs Spring Container</h3><p>In Core Java:</p><pre>public static void main(String[] args) {<br>EmailService emailService =<br>            new EmailService();<br>    OrderService orderService =<br>            new OrderService(emailService);<br>}</pre><p>The main method manages everything.</p><p>In Spring Boot:</p><pre>@SpringBootApplication<br>public class Application {<br>public static void main(String[] args) {<br>        SpringApplication.run(<br>                Application.class,<br>                args);<br>    }<br>}</pre><p>Now Spring takes responsibility for:</p><ul><li>Creating objects</li><li>Managing dependencies</li><li>Maintaining bean lifecycle</li></ul><p>The IoC Container effectively replaces most of the manual object management we perform inside the main method.</p><h3>Complete Flow of Dependency Injection in Spring</h3><pre>Application Starts<br>        |<br>        V<br>Spring IoC Container Starts<br>        |<br>        V<br>Scans Components<br>        |<br>        V<br>Creates Beans<br>        |<br>        V<br>Resolves Dependencies<br>        |<br>        V<br>Injects Dependencies<br>        |<br>        V<br>Application Ready</pre><h3>Frequently Asked Interview Questions</h3><h3>What is Dependency Injection?</h3><p>Dependency Injection is a design pattern where dependencies are supplied from outside rather than created inside the class.</p><h3>What is Inversion of Control?</h3><p>Inversion of Control is a principle where control of object creation and dependency management is transferred from the application to the framework.</p><h3>What is the relationship between IoC and DI?</h3><p>IoC is the principle, while Dependency Injection is the technique used to achieve IoC.</p><h3>What is a Spring Bean?</h3><p>A Spring Bean is an object managed by the Spring IoC Container.</p><h3>Which Dependency Injection type is preferred?</h3><p>Constructor Injection is preferred because it:</p><ul><li>Makes dependencies explicit</li><li>Supports immutability</li><li>Improves testability</li><li>Prevents null dependencies</li></ul><h3>Conclusion</h3><p>Dependency Injection and Inversion of Control form the foundation of the Spring Framework.</p><p>Dependency Injection helps create loosely coupled and testable applications, while Inversion of Control transfers object management responsibilities to the framework.</p><p>The Spring IoC Container creates, manages, and wires beans automatically, allowing developers to focus on business logic instead of object creation and dependency management.</p><p>Mastering these concepts is the first major step toward becoming proficient in Spring Boot and enterprise Java development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b56de1968ab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>