🚀 Understanding File Uploads in Spring: MultipartResolver & MultipartHttpServletRequest In modern web applications, handling file uploads is a critical feature. Spring provides powerful abstractions to simplify this process — mainly through MultipartResolver and MultipartHttpServletRequest. 🔹 What is MultipartResolver? MultipartResolver is a Spring interface used to parse HTTP requests containing file uploads (multipart/form-data). 👉 It acts as a bridge between the raw HTTP request and structured file data. 📌 Key Responsibilities: Detects multipart requests Parses request into files + parameters Converts them into a usable request object 📌 Common Implementations: StandardServletMultipartResolver CommonsMultipartResolver 🔄 Flow of MultipartResolver 1️⃣ Client sends a request with multipart/form-data (file upload) 2️⃣ Spring DispatcherServlet checks for MultipartResolver 3️⃣ MultipartResolver parses the request 4️⃣ Wraps it into MultipartHttpServletRequest 5️⃣ Controller receives structured data (files + params) 👉 This flow ensures clean separation of concerns and simplifies file handling. 🔹 What is MultipartHttpServletRequest? MultipartHttpServletRequest is a specialized version of HttpServletRequest. 👉 It provides direct access to uploaded files and form data. 📌 Key Features: Retrieve files using getFile() or getFiles() Access file metadata (name, size, type) Handle multiple file uploads easily 💡 Why It Matters? Without these abstractions, developers would manually parse complex request streams. With Spring: ✔ Cleaner code ✔ Better maintainability ✔ Seamless file handling 🔥 Real-World Use Cases Profile image upload Document submission systems Media sharing platforms 📌 Conclusion MultipartResolver handles the processing, while MultipartHttpServletRequest provides access to the parsed data. Together, they make file upload handling in Spring simple, efficient, and scalable. #Java #SpringBoot #BackendDevelopment #WebDevelopment #SoftwareEngineering #InterviewPrep
Spring File Uploads: MultipartResolver & MultipartHttpServletRequest
More Relevant Posts
-
🚀 @Component vs @Service vs @Repository — Same or Different? Most developers think all 3 are the same… But there’s a small difference that matters 👇 --- 👉 First, the truth: All three are stereotype annotations in Spring. ✔ @Component ✔ @Service ✔ @Repository Under the hood → ALL are detected during component scanning → All are registered as beans in ApplicationContext --- 💡 Then why 3 different annotations? 👉 It’s about semantic meaning + special behavior --- 1️⃣ @Component → Generic annotation → Used for any Spring-managed class Example: @Component public class EmailUtil {} --- 2️⃣ @Service → Used for business logic layer Example: @Service public class OrderService { // business logic } ✔ Makes code more readable ✔ Helps in layered architecture --- 3️⃣ @Repository → Used for database layer (DAO) Example: @Repository public class UserRepository { // DB operations } 🔥 Special feature: Spring automatically handles database exceptions → Converts them into Spring exceptions (DataAccessException) --- ⚡ Real-world layering: Controller → Service → Repository → DB Each annotation clearly defines responsibility ✅ --- ❌ Common mistake: Using @Component everywhere → Code works, but design becomes messy --- 📌 Key Takeaway: All are technically same… But using the right one makes your code clean, structured, and professional. --- Follow for more such deep dives 🚀 #SpringBoot #Java #BackendDevelopment #SoftwareEngineer
To view or add a comment, sign in
-
-
Most developers equate slow APIs with bad code. However, the issue often lies elsewhere. Consider this scenario: You have a query that appears perfectly fine: SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id Yet, the API is painfully slow. Upon checking the execution plan, you find: NESTED LOOP → TABLE ACCESS FULL ORDERS → INDEX SCAN CUSTOMERS At first glance, this seems acceptable. But here's the reality: for each row in orders, the database is scanning and filtering again. If orders contain 1 million rows, that's 1 million loops. The real issue wasn’t the JOIN; it was the database's execution method. After adding an index: CREATE INDEX idx_orders_date ON orders(created_at); The execution plan changed to: INDEX RANGE SCAN ORDERS → INDEX SCAN CUSTOMERS As a result, query time dropped significantly. Key lessons learned include: • Nested Loop is efficient only when: → the outer table is small → the inner table is indexed • Hash Join is preferable when: → both tables are large → there are no useful indexes • Common performance issues stem from: → full table scans → incorrect join order → missing indexes → outdated statistics A common mistake is this Java code: for (Order o : orders) { o.getCustomer(); } This essentially creates a nested loop at the application level (N+1 query problem). Final takeaway: Don’t just write queries; understand how the database executes them. That's where true performance improvements occur. If you've resolved a slow query using execution plans, sharing your experience would be valuable. #BackendDevelopment #DatabaseOptimization #SQLPerformance #QueryOptimization #SystemDesign #SoftwareEngineering #Java #SpringBoot #APIPerformance #TechLearning #Developers #Coding #PerformanceTuning #Scalability #DistributedSystems #DataEngineering #Debugging #TechTips #LearnInPublic #EngineeringLife
To view or add a comment, sign in
-
🚀 Day 6 — Core Spring Annotations (Must Know 🔥) Today I learned the most important Spring annotations 👉 These are used in almost every real project 💡 1. @Component 👉 Marks a class as Spring Bean @Component class User {} 💡 2. @Service 👉 Used for business logic layer @Service class UserService {} 💡 3. @Repository 👉 Used for database layer @Repository class UserRepository {} 💡 4. @Controller 👉 Handles web requests @Controller class UserController {} 💡 5. @Autowired 👉 Injects dependency automatically @Autowired UserService service; ⚡ Important Point: 👉 All above annotations need @ComponentScan 📌 Key Takeaways: @Component → generic bean @Service → business logic @Repository → DB layer @Controller → request handling @Autowired → dependency injection 💡 One line I learned: 👉 Annotations replaced XML configuration 💬 Which annotation confused you the most? Day 6 done ✅ #Spring #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #SpringBoot #Developers
To view or add a comment, sign in
-
-
In a Spring Boot application, code is structured into layers to keep things clean, maintainable, and scalable. The most common layers are Controller, Service, and Repository each with a clear responsibility. i)Controller * Entry point of the application. * Handles incoming HTTP requests (GET, POST, etc.). * Accepts request data (usually via DTOs). * Returns response to the client. ii)Service * Contains business logic. * Processes and validates data. * Converts DTO ↔ Entity. iii)Repository * Connects with the database. * Performs CRUD operations. * Works directly with Entity objects. Request Flow (Step-by-Step): Let’s understand what happens when a user sends a request: 1. Client sends request Example: `POST /users` with JSON data. 2. Controller receives request * Maps request to a method. * Accepts data in a DTO. ``` @PostMapping("/users") public UserDTO createUser(@RequestBody UserDTO userDTO) { return userService.createUser(userDTO); } ``` 3. Controller → Service * Passes DTO to Service layer. 4. Service processes data * Applies business logic. * Converts DTO → Entity. ``` User user = new User(); user.setName(userDTO.getName()); ``` 5. Service → Repository * Calls repository to save data. ``` userRepository.save(user); ``` 6. Repository → Database * Data is stored in DB. 7. Response Flow Back * Repository → Service → Controller. * Entity converted back to DTO. * Response sent to client. Why DTO is Used: * Prevents exposing internal entity structure. * Controls input/output data. * Improves security. * Keeps layers independent. Why This Architecture Matters: * Clear separation of concerns * Easier debugging & testing * Scalable and maintainable codebase #Java #Spring #SpringBoot #BackendDevelopment #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
-
Why CRUD thinking is not enough for serious backend systems Not every business problem should be modeled as simple CRUD A lot of applications start as: - Create - Read - Update - Delete And that’s fine in simple cases. But serious business systems usually have behaviors that are not well represented by CRUD. An order is not just “updated”. It can be: - placed - confirmed - cancelled - paid - expired - refunded Inventory is not just “edited”. It can be: - reserved - released - restocked - confirmed Once you model everything as generic updates, you start losing business meaning. That’s when bugs increase. Because the system no longer expresses the real rules clearly. Good backend design often means moving from: data manipulation to business behavior modeling That’s a major difference between simple coding and system design. #DDD #BackendEngineering #Java #SpringBoot #SystemDesign #SoftwareArchitecture
To view or add a comment, sign in
-
-
Most developers learn how to build APIs. But very few understand how APIs actually behave in production. Let’s break this down simply When you hit an API, it’s not just a request → response cycle. There are multiple layers involved: 1. Client Layer - Your frontend or app sends a request 2. Network Layer - DNS, internet routing, latency, sometimes CDNs 3. Gateway / Load Balancer - Routes traffic to the right server 4. Server Layer - Controller handles the request 5. Business Logic Layer - Core application logic runs here 6. Database Layer - Data is fetched or updated (often becomes a bottleneck at scale) 7. Response Layer - Data is returned Sounds simple. Right? But here’s what points got missed: - Each layer adds time - Each layer can fail - Each layer can be optimized Now imagine this: Your API works perfectly with 10 users. But suddenly you have thousands of users. What changes? - Database may becomes a performance bottleneck - Response time increases - Server starts slowing down - Users experience delays This is where backend engineering becomes interesting. That's when these concepts come into play: - Caching (Redis, CDN) - Why hit the database every time when you can serve it in milliseconds? - Load balancing - Don’t let one server struggle—spread the traffic, spread the load. - Efficient queries & indexing - A slow query can break a fast system. - Rate limiting - Not all traffic is good traffic—control it before it controls you. This is the difference between Writing code & Building systems Here are the illustration images from the related talk. #java #backenddevelopment #springboot #softwareengineering #systemdesign #apis #programming #developers
To view or add a comment, sign in
-
-
🚀 Day 28 – Bean Scopes: Managing Object Lifecycles the Right Way In Spring-based systems, Bean Scope defines how long an object lives and how many instances are created. It directly impacts memory usage, performance, and thread safety — making it an important architectural decision. 🔹 1. Singleton (Default Scope) ✔ One instance per Spring container ✔ Shared across the application ➡ Best for: Stateless services Utility components ⚠️ Be careful with mutable state (thread-safety concerns) 🔹 2. Prototype Scope ✔ New instance every time requested ➡ Best for: Stateful objects Short-lived processing logic ⚠️ Spring does NOT manage full lifecycle (e.g., destruction) 🔹 3. Request Scope (Web Apps) ✔ One bean per HTTP request ➡ Best for: Request-specific data User context 🔹 4. Session Scope ✔ One bean per user session ➡ Best for: User preferences Session-level caching ⚠️ Can increase memory usage if misused 🔹 5. Application Scope ✔ One bean per ServletContext ➡ Shared across the entire application lifecycle ➡ Rarely used but useful for global configs 🔹 6. Choosing the Right Scope Matters Wrong scope can lead to: ❌ Memory leaks ❌ Concurrency issues ❌ Unexpected behavior ➡ Always align scope with object responsibility & lifecycle 🔹 7. Stateless Design is King Prefer singleton + stateless beans ➡ Easier scaling ➡ Better performance ➡ Fewer concurrency bugs 🔹 8. Scope + Dependency Injection Gotcha Injecting prototype into singleton? ➡ You’ll still get a single instance unless handled properly ➡ Use ObjectFactory / Provider for dynamic resolution 🔥 Architect’s Takeaway Bean scope is not just configuration — it’s an architectural decision. Choosing the right scope ensures: ✔ Efficient memory usage ✔ Better scalability ✔ Thread-safe designs ✔ Predictable behavior 💬 Which bean scope do you use the most — and have you ever faced issues due to wrong scope? #100DaysOfJavaArchitecture #SpringBoot #BeanScopes #Java #Microservices #SystemDesign #TechLeadership
To view or add a comment, sign in
-
-
When building scalable backend systems, we often deal with hierarchical data structures — think file systems, organization trees, menu structures, or nested API responses. That’s where the Composite Design Pattern shines. 💡 👉 It allows us to treat individual objects (leaf nodes) and groups of objects (composites) in the same way using a common interface. 💻 Why it matters in backend development: ✔ Simplifies handling of tree-like data structures ✔ Promotes clean, maintainable, and extensible code ✔ Reduces conditional logic when dealing with nested objects ✔ Aligns well with recursive operations (like traversals) 🧠 Real-world backend examples: File systems (Files & Folders) Organization hierarchy (Employee & Manager) Comment systems (Comments & Replies) Menu rendering in APIs ⚙️ Core Idea: Define a common interface (say Component) that both: Leaf (single object) Composite (group of objects) implement. This lets you write code like: component.operation(); …without worrying whether it's a single object or a collection. 🔥 Key takeaway: “Composite Pattern helps you build tree structures and treat individual and grouped objects uniformly.” Check it out - https://lnkd.in/gQQfhWJK As a Java backend developer, mastering patterns like Composite helps in writing clean architecture and scalable systems — something every production-grade application demands. #Java #BackendDevelopment #DesignPatterns #SystemDesign #LLD #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Spring Core DAY 12 – Bean Scopes 🚀 Bean Scopes in Spring – What Are They? In Spring Framework, a Bean is an object managed by the Spring IOC Container. But here’s the important question 🤔 👉 How many instances of that bean should Spring create? That’s where Bean Scope comes into the picture. Simply put, Bean Scope defines the lifecycle and visibility of a bean inside the Spring container. 🔹 1️⃣ Singleton Scope (Default) ✔ Only one object is created per Spring container ✔ The same instance is shared everywhere ✔ Default scope in Spring 📌 This means: If 10 different classes use the same bean Spring will still create only ONE object @Component @Scope("singleton") public class MyService { } 💡 Best used for: Service classes DAO/Repository classes Configuration classes Stateless beans ⚡ Advantage: Better memory management Improved performance Centralized control 🔹 2️⃣ Prototype Scope ✔ A new object is created every time the bean is requested ✔ No shared instance @Component @Scope("prototype") public class MyBean { } 📌 This means: Every getBean() call returns a new object Each injection creates a fresh instance 💡 Best used for: Stateful beans Temporary objects User-specific data handling ⚠ Important: Spring does NOT manage full lifecycle of Prototype beans after creation. Destruction callbacks are not called automatically. 🆚 Singleton vs Prototype (Simple Difference) Feature Singleton Prototype Instances One Multiple Default? Yes No Memory Usage Low Higher Lifecycle Fully managed Only initialization 🧠 Why Bean Scope Matters? Choosing the correct scope: ✔ Improves performance ✔ Avoids memory leaks ✔ Prevents unexpected behavior ✔ Ensures thread safety ✔ Frequently asked in interviews 🎯 Real-World Example Imagine a DatabaseService Bean 🔹 Singleton → One shared connection manager 🔹 Prototype → New object for each transaction Wrong scope selection can cause: ❌ Performance issues ❌ Data inconsistency ❌ Concurrency problems 🏆 Pro Interview Tip 👉 What happens when a Prototype bean is injected into a Singleton bean? Only one instance gets injected (because injection happens once during Singleton creation). To get a new instance every time, use: ObjectFactory Provider @Lookup method injection 📌 In Short: Bean Scope = How many objects Spring creates Singleton → One shared object Prototype → New object every request Choosing the right scope = Clean + Efficient + Scalable application ⚡ hashtag#BeanScope hashtag#SpringCore hashtag#Singleton hashtag#Prototype
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