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
Spring Boot @RequestMapping Annotation Explained
More Relevant Posts
-
🚀 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
-
-
How DispatcherServlet Works Internally in Spring Boot 👇 🌱 Understanding How DispatcherServlet Works Internally in Spring Boot🚀 In Spring Boot applications, every HTTP request is handled by a central component called DispatcherServlet. It acts as the Front Controller of the Spring MVC architecture. This means all incoming requests first pass through DispatcherServlet, which decides how they should be processed. 🔍 What is DispatcherServlet? DispatcherServlet is the core component of Spring MVC responsible for: Receiving HTTP requests Finding the correct controller Executing business logic Returning the response to the client It acts as a traffic controller for web requests. 🔄 Internal Working Flow 1️⃣ Client Sends Request Example request: GET /users/1 The request first reaches DispatcherServlet. 2️⃣ Handler Mapping DispatcherServlet asks HandlerMapping: “Which controller should handle this request?” Spring finds the appropriate controller method. Example: @GetMapping("/users/{id}") public User getUser(@PathVariable int id) { return userService.getUser(id); } 3️⃣ Handler Adapter DispatcherServlet calls HandlerAdapter to execute the controller method. This step ensures that different types of handlers can be executed uniformly. 4️⃣ Controller Executes Logic The controller calls: Service Layer Repository Layer Database to process the request. 5️⃣ Response Returned Controller returns data: JSON (REST API) View (HTML page) Example: { "id": 1, "name": "John" } 6️⃣ View Resolver (For MVC Apps) If the application returns a view name, Spring uses ViewResolver to locate the actual view. Example: return "home"; Spring finds: home.html 📊 Complete Request Flow Client Request ⬇ DispatcherServlet ⬇ HandlerMapping ⬇ HandlerAdapter ⬇ Controller ⬇ Service ⬇ Repository ⬇ Response Returned to Client #SpringBoot #SpringMVC #Java #BackendDevelopment #LearningInPublic #JavaDeveloper
To view or add a comment, sign in
-
-
☕ @SpringBootApplication — The Magic Annotation Unpacked One annotation to rule them all. But do you know what's actually inside it? @SpringBootApplication is a convenience annotation that combines three powerful ones: @SpringBootApplication // is equivalent to: @Configuration @EnableAutoConfiguration @ComponentScan public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } Here's what each does: • @Configuration — marks this class as a source of bean definitions (replaces XML config) • @ComponentScan — tells Spring to scan the current package and subpackages for @Component, @Service, @Repository, @Controller • @EnableAutoConfiguration — the real magic: Spring Boot reads your classpath and auto-configures beans (e.g., sees H2 → configures DataSource automatically) You can customize the scan: @SpringBootApplication(scanBasePackages = {"com.myapp.service", "com.myapp.api"}) Or exclude an auto-configuration you don't want: @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #SpringFramework
To view or add a comment, sign in
-
🚀 @RestController vs @Controller — Do You Know the Real Difference? Most Spring Boot developers reach for @RestController without thinking twice. But knowing why it exists separates good engineers from great ones. @Controller is the classic Spring MVC annotation — it marks a class as a web controller that returns view names (like Thymeleaf templates). To return JSON from a @Controller method, you must explicitly add @ResponseBody. @RestController is simply a convenience annotation that combines @Controller + @ResponseBody. Every method automatically serializes the return value to JSON/XML via Jackson — no extra annotation needed. // Classic MVC — returns a Thymeleaf view @Controller public class PageController { @GetMapping("/home") public String home(Model model) { model.addAttribute("user", "Janis"); return "home"; // resolves to home.html } } // REST API — returns JSON automatically @RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.findById(id); // auto-serialized to JSON } } The rule is simple: → Building a REST API? Always use @RestController. → Building server-side rendered views (SSR)? Use @Controller. In modern microservice architectures, @RestController dominates — because APIs communicate via JSON, not HTML pages. #Java #SpringBoot #BackendDevelopment #REST #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
📌 Spring Boot Annotation Series Part 17 – @GetMapping The @GetMapping annotation is used to handle HTTP GET requests in Spring Boot applications. It is part of the Spring Framework and is mainly used in REST APIs. 🔹 What is @GetMapping? @GetMapping is a shortcut for: @RequestMapping(method = RequestMethod.GET) Instead of writing the long version, we use this cleaner and more readable annotation. 🔹 Basic Example - @RestController @RequestMapping("/api") public class UserController { @GetMapping("/users") public String getUsers() { return "List of users"; } } 👉 This handles: GET http://localhost:8080/api/users 🔹 When Do We Use GET? ✔ To fetch data ✔ No modification of data ✔ Safe and idempotent operation Example use cases: - Get all users - Get user by ID - Fetch product list - Retrieve order details 🔹 In Simple Words @GetMapping handles read operations in REST APIs. When a GET request hits the URL, Spring executes the mapped method. #SpringBoot #Java #RESTAPI #BackendDevelopment #InterviewPreparation #LearningInPublic
To view or add a comment, sign in
-
Spring Security: Servlet vs. Reactive – Which one to choose? 🛡️ Choosing between Servlet and Reactive isn’t just a technical choice… 👉 It’s an architectural decision that directly impacts scalability, performance, and debugging. Here’s a quick breakdown from my recent learnings 👇 🔵 Servlet Stack (Spring MVC) Built on the Servlet API Uses Filters + SecurityContextHolder (ThreadLocal) Follows blocking I/O + thread-per-request model ✅ Best suited for: Traditional applications RDBMS-heavy systems Business logic–intensive services (Payments, Orders) ⚠️ Limitation: Threads remain occupied during I/O → limits scalability under high load 🟢 Reactive Stack (WebFlux) Built on Project Reactor Uses WebFilter + ReactiveSecurityContextHolder Follows non-blocking I/O + event-loop model ✅ Best suited for: High-concurrency microservices API Gateways / Streaming / Notifications Cloud-native, event-driven systems ⚠️ Challenge: Debugging async flows is harder Requires a shift in thinking (no ThreadLocal) 💡 Key Insight: 👉 It’s not about which is better 👉 It’s about where it fits My rule of thumb: 🔹 CPU-heavy → Servlet 🔹 I/O-heavy → Reactive ⚠️ One important lesson: You cannot mix both stacks in a single Spring Boot app cleanly. Spring will default to Servlet → Reactive may silently break. 📚 Still learning and exploring deeper into backend systems, trying to understand things beyond just configuration. 💬 Would love to hear from others — Which stack are you using in your projects? #SpringBoot #SpringSecurity #Java #BackendDevelopment #Microservices #WebFlux #LearningInPublic #Developers
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
-
-
🚀 Mastering HTTP Method Mappings in Spring Boot One annotation decides whether your endpoint lives or dies — and most developers don't fully understand the difference between them. In Spring Boot, @RequestMapping is the parent of all HTTP-method-specific shortcuts. But in real projects, you'll almost never see it alone — instead, we use @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping to make code readable and intentional. Here's why it matters: @RestController @RequestMapping("/api/products") public class ProductController { @GetMapping // GET /api/products public List<Product> getAll() { ... } @PostMapping // POST /api/products public Product create(@RequestBody Product p) { ... } @PutMapping("/{id}") // PUT /api/products/1 public Product update(@PathVariable Long id, @RequestBody Product p) { ... } @DeleteMapping("/{id}") // DELETE /api/products/1 public void delete(@PathVariable Long id) { ... } } Clean, self-documenting, and follows REST conventions. Key takeaway: Use @RequestMapping at class level for base paths, and specific annotations at method level for clarity. Mixing HTTP methods inside one @RequestMapping is a code smell. #Java #SpringBoot #BackendDevelopment #REST #Programming
To view or add a comment, sign in
-
Day 03 – Bean Scopes (Singleton vs Prototype vs Request vs Session) What is Bean Scope? Bean Scope defines: • How many instances of a bean Spring creates • How long the bean lives By default, Spring creates only one object per bean. ==================================== Singleton (Default Scope) ==================================== Only ONE object is created for the entire application. @Component public class StudentService { } Spring creates one StudentService object and shares it everywhere. Memory efficient Best for stateless services Used in most backend applications In real projects: Controllers, Services, Repositories → Mostly Singleton ===================================== Prototype Scope ===================================== Every time the bean is requested → New object is created. @Component @Scope("prototype") public class StudentService { } Used when: • Object holds state • You need independent instances Not very common in REST APIs, but useful in specific cases. ======================================= Request Scope (Web Applications) ======================================= One bean per HTTP request. Each client request gets a new object. Used when: • You need request-specific data • Temporary processing per request ==================================== Session Scope ==================================== One bean per user session. Each logged-in user gets a separate object. Used when: • Storing user-specific session data Why This Matters in Real Backend Systems? Because scope : • Memory usage • Performance • Thread safety • Scalability ================================== Today’s Learning Spring does not just create objects. Understanding Bean Scope helps you think like a backend engineer. Tomorrow: Types of Dependency Injection (Constructor vs Setter vs Field) #Java #SpringBoot #SpringFramework #BackendDevelopment #Microservices #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
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