What Actually Happens When We Use @RestController in Spring Boot? When I first saw the annotation @RestController, I honestly didn’t know why it was used. Everyone was using it ,So I started using too. But one day I paused and asked myself: What is Spring actually doing when I write @RestController? That’s when things slowly started making sense. In Spring , there are two common annotations we used with Controllers: 1.@Controller 2.@RestController At first, they look almost the same. But they behave very differently. ->@Controller When we use @Controller , Spring assumes we are returning a view. That means : It expects an HTML page. This is mostly used in traditional Spring MVC applications where the backend returns web pages. -> @RestController When we use @RestController, we are telling Spring: i . Don’t return a view. ii . Return the data directly in the response body. Internally, @RestController is simply a combination of: @Controller + @ResponseBody So instead of rendering HTML , Spring sends JSON directly to the client. That’s why in REST APIs, we use @RestController. Now when I use @RestController, I understand what it’s telling Spring to do. Understanding little things like this , changing how I see backend development. More tomorrow 🚀 #SpringBoot #Java #BackendDevelopment #LearningInPublic #SoftwareEngineering
Omkar Dumpa’s Post
More Relevant Posts
-
🚀 Day 6/100: Spring Boot From Zero to Production Topic: @SpringBootApplication Annotation Your setup is done, your dependencies are added, and now you are ready to write some actual code and business logic. It all begins from your Main Class. This class usually carries the name of your application and contains a main function, the exact point where the execution begins. But there is one very important part of this main class: the @Annotation. In simple terms, an annotation is metadata written after an @ sign. it tells the compiler and the framework specific information about your code. In our case, the star of the show is @SpringBootApplication. This is a "Meta-Annotation," meaning it’s a powerful 3-in-1 combo that keeps your code clean and organized: 1. @Configuration This marks the class as a source of bean definitions. It tells Spring that this class can contain methods annotated with @Bean. In the old days of Spring, you had to manage everything in bulky XML files. With this, we use pure Java to define our infrastructure. 2. @EnableAutoConfiguration This is the "secret sauce" that makes Spring Boot feel like magic. The Role: It tells Spring Boot to start adding beans based on what it finds on your classpath. If it sees h2.jar, it sets up an in-memory database for you. No more Boilerplate Nightmares. You don't have to manually set up a Data Source unless you want to override the defaults. 3. @ComponentScan 🔍 Think of this as the "Search Party" for your project. It tells Spring to hunt for other components, configurations, and services in your packages. It specifically looks for: @Component @Service @Repository @RestController The Scope: By default, it scans the package containing your main class and all sub-packages. This is why we always keep the main class in the root package! We’ve cracked open the entry point of every Spring Boot app. 🔓 See you in the next post. #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend
To view or add a comment, sign in
-
-
🚀 Day 10/100: Spring Boot From Zero to Production Topic: Bean Scopes 🧩 Remember when we talked about Beans in Java? Quick recap: Beans are just instances of your classes that live inside the Spring Container. Spring manages their lifecycle and handles Dependency Injection so you don't have to manually "new" them up every time. But there is a lot more to it than just creating them. We need to talk about Bean Scopes. 1. The Default: Singleton By default, all beans in Spring are Singletons. This means Spring creates the instance once and shares that same exact instance every single time it’s needed. For components like Services, Repositories, or Controllers, a single instance is perfect because they are usually stateless they just perform actions. 2. The Alternative: Prototype But what if a single instance isn't enough? What if your bean holds state-specific data or thread-specific info where one user's data shouldn't leak into another's? That’s where the Prototype scope comes in. With this, Spring creates a brand-new instance every time the bean is requested. ⚠️ Word of caution: Use this wisely! Creating too many prototype beans when they aren't needed can put a heavy load on your memory. 3. Web-Aware Scopes If you are building web apps, Spring offers even more specialized scopes: Request Scope: A new bean for every single HTTP request. Session Scope: A bean that lives as long as the user's HTTP session. Choosing the right scope is all about balancing memory efficiency with data integrity. How do you usually decide between Singleton and Prototype in your projects? Let’s discuss below! 👇 #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend
To view or add a comment, sign in
-
-
Hi everyone 👋 Continuing the Spring Boot Annotation Series, today let’s understand one of the most important web annotations 👇 📌 Spring Boot Annotation Series Part 16– @RequestMapping The @RequestMapping annotation is used to map HTTP requests(like GET, POST etc) to handler methods in a controller. It is part of Spring Framework and is mainly used in Spring MVC. 🔹 What does @RequestMapping do? It defines: - URL path - HTTP method (GET, POST, etc.) - Request parameters - Headers - Consumes / Produces (Content-Type) 🔹 Basic Example - @RestController @RequestMapping("/api") public class UserController { @RequestMapping("/users") public String getUsers() { return "List of users"; } } 👉 This maps to: http://localhost:8080/api/users 🔹 Specifying HTTP Method - @RequestMapping(value = "/users", method = RequestMethod.GET) public String getUsers() { return "Users"; } But nowadays we prefer: @GetMapping("/users") 🔹 Where Can We Use It? ✅ At Class Level → Base URL ✅ At Method Level → Specific endpoint Example: @RequestMapping("/api") // class level @GetMapping("/users") // method level Final URL → /api/users 🔹 In Simple Words @RequestMapping connects a URL to a controller method. It tells Spring: “When this request comes, execute this method.” #SpringBoot #Java #SpringMVC #BackendDevelopment #InterviewPreparation #LearningInPublic
To view or add a comment, sign in
-
🚀 @RequestBody & @ResponseBody — The Magic Behind JSON in Spring Boot Most developers use these annotations daily without thinking about what actually happens under the hood. Let me change that. When a client sends JSON to your REST API, Spring Boot doesn't magically "just know" how to convert it into a Java object. That's @RequestBody at work — it tells the HttpMessageConverter (Jackson, by default) to deserialize the incoming JSON stream into your method parameter. @PostMapping("/users") public ResponseEntity<UserResponse> createUser( @RequestBody UserRequest request) { // 'request' is fully populated from JSON body return ResponseEntity.status(201) .body(service.create(request)); } @ResponseBody does the reverse — it serializes your return value into JSON and writes it directly to the HTTP response. When you use @RestController, @ResponseBody is already included. That's the only difference between @Controller and @RestController. What actually happens: 1. Request arrives → DispatcherServlet routes it 2. HttpMessageConverter checks Content-Type: application/json 3. Jackson's ObjectMapper deserializes JSON → Java object 4. Your method runs 5. Return value → ObjectMapper serializes → JSON response Common pitfalls: • Missing Content-Type: application/json header → 415 Unsupported Media Type • No default constructor on your DTO → deserialization fails • Field names mismatch (use @JsonProperty to fix) #Java #SpringBoot #BackendDevelopment #REST #API #SoftwareEngineering
To view or add a comment, sign in
-
📅 Spring Boot DAY 20 – @RestController vs @Controller Difference between @RestController & @Controller 👇 In Spring Boot, both annotations are used to handle HTTP requests — but their purpose is different. 🔹 @Controller @Controller is used in Spring MVC applications where we return a View (HTML page). ✔ Returns view name (like index.html ) ✔ Used with Thymeleaf / JSP ✔ Data is passed to the view using Model Example: @Controller public class HomeController { @GetMapping("/home") public String home(Model model) { model.addAttribute("message", "Welcome!"); return "home"; // returns home.html } } 👉 Best for Web applications (Frontend + Backend together) 🔹 @RestController @RestController is used in REST APIs where we return JSON or XML data instead of a view. ✔ Returns data directly ✔ Automatically converts Java object → JSON ✔ Used for backend services Example: @RestController public class UserController { @GetMapping("/user") public User getUser() { return new User(1, "Gajanan"); } } 👉 Output: { "id": 1, "name": "Gajanan" } 🔥 Key Difference @Controller@RestControllerReturns HTML ViewReturns JSON/XMLUsed in MVC appsUsed in REST APIsNeeds @ResponseBody to return JSONNo need for @ResponseBody💡 Important Concept 👉 @RestController = @Controller + @ResponseBody @ResponseBody tells Spring to write return value directly into HTTP response body. That’s why modern microservices & backend APIs use @RestController. 🚀 When to Use What? ✔ Building a website with UI → Use @Controller ✔ Building API for Mobile/Web frontend → Use @RestController Most modern backend applications use @RestController. #RestController #Controller #SpringBoot #JavaAPI #BackendDevelopment
To view or add a comment, sign in
-
-
⚙️ Spring Boot Auto-Configuration — What Actually Happens Behind the Scenes Spring Boot feels “magical” because of auto-configuration. But internally it follows a very structured process. When your application starts, Spring Boot loads auto-configuration classes using: spring.factories (Spring Boot 2) AutoConfiguration.imports (Spring Boot 3) These files list classes that Spring Boot should evaluate during startup. Example: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration Spring Boot does NOT load everything blindly. Each auto-configuration class contains conditional annotations such as: • @ConditionalOnClass • @ConditionalOnMissingBean • @ConditionalOnProperty Example: @Configuration @ConditionalOnClass(DataSource.class) @ConditionalOnMissingBean(DataSource.class) Meaning: ✔ If DataSource exists in classpath ✔ And user has not defined a DataSource bean ➡ Spring Boot will auto-create one. This is how Boot automatically configures: • DataSources • Jackson ObjectMapper • Web MVC • Security filters without explicit configuration. I share more deep Spring Boot internals and backend engineering topics here: 👉 https://lnkd.in/d4wPvvN3 If this helped clarify Spring Boot Auto-Configuration, comment: “AutoConfig” Happy to connect with engineers interested in Spring internals and backend architecture. #SpringBoot #Java #BackendEngineering #SoftwareArchitecture #Microservices #JavaDeveloper #SystemDesign #SpringFramework #TechLearning
To view or add a comment, sign in
-
🔄 How Does Bean Lifecycle Work in Spring Boot? While learning Spring Boot deeply, I explored how a bean is created and managed internally. Here’s the simplified lifecycle: 1️⃣ Bean Instantiation Spring creates the object (bean) using constructor. 2️⃣ Dependency Injection Required dependencies are injected using @Autowired (or constructor injection). 3️⃣ Bean Initialization If methods are annotated with @PostConstruct, they are executed after dependencies are set. 4️⃣ Bean Ready for Use The bean is now available inside the IoC container. 5️⃣ Bean Destruction When the application shuts down, methods annotated with @PreDestroy are executed. 💡 Important: Spring manages the complete lifecycle — from creation to destruction. This is why Spring applications are clean, maintainable, and loosely coupled. Understanding internals makes backend development stronger 💻 #SpringBoot #Java #BackendDeveloper #BeanLifecycle #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Day 8/100: Spring Boot From Zero to Production Topic: Stereotype Annotations Honestly, this series is starting to test my consistency but I'm also genuinely beginning to enjoy it. 😄 Today we continue the annotations journey and dive into some major class-level annotations you'll use constantly in Spring Boot. What they all have in common: Before breaking them down, here's what these annotations share: 🏭 Spring automatically creates beans for these classes 🔄 Spring manages them for dependency injection 🎯 Each one keeps your concerns cleanly separated The Big Five: 1. @Component: The base stereotype annotation. Marks a class as a Spring-managed bean. The others below are all specializations of this. 2. @Service: Used for your business logic and use-case implementations. This layer lives between your web entry points and your database handles — it's where the real work happens. 3. @Repository: Designates the class as a DAO (Data Access Object). This is the layer that talks directly to the database and handles all your database interactions. 4. @Controller: Your web entry point. Tells Spring that this is where incoming web requests will arrive. 5. @RestController ⭐: This one is a personal favourite, a beautiful Spring Boot shortcut. It combines two annotations under the hood: @Controller: marks the class as a web request handler, a specialized @Component. @ResponseBody: automatically binds the return value of your methods to the web response body, no ViewResolver needed. So instead of writing both every time, you just write one. Clean. 🙌 Each annotation has a clear job. When you respect these boundaries, your codebase stays readable, testable, and maintainable as it scales. More content coming tomorrow. Stay consistent! 💪 #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend
To view or add a comment, sign in
-
-
Filter vs Interceptor in Spring Boot 👇 🌱 Understanding Filter vs Interceptor in Spring Boot 🚀 While working with web applications in Spring Boot, we often need to perform tasks like: Logging requests Authentication & authorization Request validation Performance monitoring To handle these before or after a request, Spring provides Filters and Interceptors. Let’s understand the difference. 🔹 What is a Filter? A Filter is part of the Servlet API and works at the web container level. It processes requests before they reach the Spring application. Common use cases: Logging CORS handling Authentication Request/Response modification Example Filter: @Component public class LoggingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Request received"); chain.doFilter(request, response); System.out.println("Response sent"); } } 🔹 What is an Interceptor? An Interceptor is part of Spring MVC and works inside the Spring framework. It intercepts requests before they reach the controller and after controller execution. Common use cases: Authentication checks Logging Request timing Authorization Example Interceptor: public class LoggingInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { System.out.println("Before controller execution"); return true; } } 🔄 Request Processing Flow Client Request ⬇ Filter ⬇ DispatcherServlet ⬇ Interceptor ⬇ Controller ⬇ Response Returned 🧠 Simple Way to Remember 👉 Filter → Works before Spring MVC 👉 Interceptor → Works inside Spring MVC #SpringBoot #SpringMVC #Java #BackendDevelopment #LearningInPublic #JavaDeveloper #SoftwareEngineering
To view or add a comment, sign in
-
-
📌 Spring Boot Annotation Series – Part 11 ✅ @Controller annotation The @Controller annotation is used to mark a class as a web controller in Spring MVC 👇 🔹 What is @Controller? @Controller is a specialization of @Component. It tells Spring: 👉 “This class will handle web requests.” 🔹 Why do we use @Controller? To handle HTTP requests To return web pages (views) To separate web layer from business logic 🔹 How does it work? When a request comes to the application: Spring maps the URL to a method in the controller The method processes the request Returns a view name (like an HTML page) 🔹 Simple example @Controller public class HomeController { @GetMapping("/home") public String home() { return "home"; // returns home.html } } 🔹 Important Note @Controller is mainly used for MVC applications that return views. If you want to return JSON responses (REST APIs), we usually use: 👉 @RestController 🔹 In simple words @Controller is used to handle web requests and return web pages. 👉 🧠 Quick Understanding @Controller handles web requests Returns view (HTML/JSP/Thymeleaf) Used in Spring MVC applications #SpringBoot #Java #ControllerAnnotation #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development