🔍 Filters vs Interceptors in Spring Boot — and why most devs mix them up Both intercept HTTP requests. Both let you run logic before and after your controller. But they live at completely different layers — and choosing the wrong one leads to subtle bugs. Here's the mental model that clears it up: Filter = Servlet Container layer. Runs before DispatcherServlet even knows a request came in. It sees everything — including static resources. Interceptor = Spring MVC layer. Runs after DispatcherServlet, before your controller method. It knows which handler is being called. The one-line rule I use: If it needs to apply to every request, use a Filter. If it needs to know which endpoint is being called, use an Interceptor. This distinction matters for: → Security — JWT pre-checks live in Filters, role validation in Interceptors → Logging — request metadata at filter level, execution time at interceptor level → Clean architecture — putting logic at the right layer keeps things testable Swipe through the full breakdown with code examples and comparison table 👇 💬 Drop a comment: Which one do you use more in production, and for what? #SpringBoot #Java #BackendDevelopment #Microservices #SpringMVC #JavaDeveloper #SoftwareArchitecture #TechInterview #SpringFramework #Programming
Spring Boot Filters vs Interceptors: Choosing the Right One
More Relevant Posts
-
Spring Boot Filters vs Interceptors — Most developers confuse this 🤯 Let’s simplify 👇 ✅ Filter (Servlet level) - Works BEFORE DispatcherServlet - Used for logging, authentication, request modification ✅ Interceptor (Spring level) - Works AFTER DispatcherServlet - Used for business-level checks 💡 Flow: Request → Filter → DispatcherServlet → Interceptor → Controller ⚡ Real use case: - Filter → JWT validation - Interceptor → role-based access 👉 Choosing wrong = messy architecture Know the difference = cleaner backend 🔥 #SpringBoot #Java #BackendDeveloper
To view or add a comment, sign in
-
Spring Boot Circular Dependency — Dangerous issue ⚠️ Example: Service A → depends on Service B Service B → depends on Service A 👉 Boom 💥 Circular dependency error 💡 Why it happens: Poor design & tight coupling Solutions 👇 ✅ Refactor logic ✅ Use constructor injection properly ✅ Introduce third service ✅ Use @Lazy (temporary fix) ⚠️ Avoid: Field injection (hard to debug) 👉 Best practice: Use constructor injection ALWAYS Clean architecture prevents these issues 🔥 #SpringBoot #Java #CleanCode
To view or add a comment, sign in
-
Spring Boot Circular Proxy Issue — Advanced trap 🤯 Even if you FIX circular dependency… Spring may still create proxies internally. 👉 This can lead to: ❌ Unexpected behavior ❌ Method not executing correctly 💡 Why? Spring uses AOP proxies (JDK / CGLIB) ⚠️ Problem: Internal method calls bypass proxy Example: Method A → calls Method B internally 👉 AOP (like @Transactional) won’t apply 🔥 Solution: ✔ Move logic to another bean ✔ Avoid internal method calls 👉 This is why some transactions “don’t work” Understanding proxies = senior-level Spring knowledge 💯 #SpringBoot #Java #AOP
To view or add a comment, sign in
-
🚀 Understanding Dependency Injection in Spring Boot with a Simple Example I recently explored one of the core concepts of the Spring Framework — Dependency Injection (DI) — by building a simple Spring Boot application. 💡 What is Dependency Injection? Dependency Injection is a design pattern where the Spring container automatically provides the required dependencies to a class, instead of the class creating them manually. This helps in achieving loose coupling and better maintainability. 🔷 Project Overview In this example, I created: A Developer class that depends on a Computer A Computer interface with multiple implementations: Laptop Desktop 🔷 How it Works ✔️ The Developer class uses @Autowired to inject the dependency: Spring automatically assigns an object of a class that implements Computer ✔️ Since there are multiple implementations (Laptop & Desktop): I used @Primary on the Laptop class This tells Spring to inject Laptop by default ✔️ The application flow: Spring Boot starts and initializes the application context Beans are created automatically using @Component Dependency is injected into the Developer class The startCoding() method executes and calls computer.code() 🔷 Key Annotations Used @SpringBootApplication → Entry point of the application @Component → Marks classes as Spring beans @Autowired → Injects dependencies automatically @Primary → Resolves ambiguity when multiple beans are available 🔷 Output 👉 "Coding in laptop......" (Because Laptop is marked as @Primary) ✨ This small implementation helped me clearly understand how Spring manages dependencies behind the scenes. #SpringBoot #Java #DependencyInjection #BackendDevelopment Thanks to Anand Kumar Buddarapu Sir.
To view or add a comment, sign in
-
Checked vs Unchecked Exceptions - Know the Difference ⚠️ 🔹 Checked Exceptions ▸ Checked at compile time ▸ Must be handled (try-catch or throws) ▸ Not handled → code won’t compile ▸ Examples: IOException, SQLException, FileNotFoundException 🔹 Unchecked Exceptions ▸ Occur at runtime ▸ No need to handle (but recommended) ▸ Extend RuntimeException ▸ Examples: NullPointerException, ArrayIndexOutOfBoundsException 💡 Simple Way to Remember → Checked = Compiler forces handling → Unchecked = Runtime errors 🚀 Best Practice ▸ Use Checked → for recoverable scenarios (e.g., file not found → retry) ▸ Use Unchecked → for programming bugs (e.g., null → fix the code) #Java #SpringBoot #ExceptionHandling #JavaDeveloper #BackendDeveloper
To view or add a comment, sign in
-
-
While building a recent Spring Boot application, I realized... The Hook: Stop defaulting to .parallelStream() to make your Java code "faster." 🛑 The Insight: It’s a common misconception that parallel streams always improve performance. Under the hood, parallelStream() uses the common ForkJoinPool. If you are executing CPU-intensive tasks on a massive dataset, it’s great. But if you are doing I/O operations (like database calls or network requests) inside that stream, you will exhaust the thread pool and bottleneck your entire application. The Pro Tip: Always benchmark. For I/O bound tasks, look into asynchronous programming (like CompletableFuture) or Java 21's Virtual Threads instead of parallel streams. #Java #PerformanceOptimization #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
Spring Boot Bean Scope — Not just Singleton 🤯 Most developers only know this: 👉 Default scope = Singleton But there’s more 👇 ✅ Prototype → New instance every time ✅ Request → Per HTTP request ✅ Session → Per user session 💡 Why it matters: ✔ Memory optimization ✔ Better state handling ⚠️ Mistake: Using singleton for stateful data ❌ 👉 Leads to concurrency issues 🔥 Real lesson: Choose scope based on use case, not default Backend bugs often start here 🚨 #SpringBoot #Java #Architecture
To view or add a comment, sign in
-
Spent 15 minutes wondering why my REST API was returning empty response The endpoint was working fine yesterday Checked the controller and service layer Everything looked correct Turns out I forgot @ResponseBody on the controller method @GetMapping("/users") public List<User> getUsers() { return userService.getAllUsers(); } Without @ResponseBody Spring tries to resolve a view instead of returning JSON Quick fix was adding @RestController instead of @Controller #Java #SpringBoot #REST #BackendDevelopment
To view or add a comment, sign in
-
🧠 Why Spring Singleton Beans Don’t Break with Multiple Users Many people ask: “If Spring creates only one Service object, what happens when 100 users hit the API?” Answer: Safe — IF your bean is stateless. Bad: ❌ storing request-specific data in class variables Good: ✅ using method-local variables only Singleton is safe because Spring shares logic, not user state. This is a very common interview question. #springboot #java
To view or add a comment, sign in
-
-
InterruptedException is not an error. It’s how threads are asked to stop. And ignoring it can make your application impossible to shut down. --- In Java’s threading model, interruption was never designed as a failure mechanism. It’s a signal. A coordination event between threads. --- Calling interrupt() is the intended way to ask a thread to stop. But it doesn’t stop it. It sets a flag. And if the thread is blocked, it may react by throwing InterruptedException. Here is the trap: when that exception is thrown, the flag is cleared. If you ignore it, you erase the signal. If you care about it, you must restore it: Thread.currentThread().interrupt(); --- This is the model. And most code ignores it. Consider this: try { queue.take(); } catch (InterruptedException e) { // ignore } Looks harmless. It’s not. From that point on, your thread behaves as if no interruption ever happened. The JVM asked it to stop. Your code said: no. This is how systems become impossible to shut down cleanly. Threads keep running. Executors don’t terminate. Shutdown hooks hang. And eventually: kill -9 This is not a rare edge case. It’s the direct consequence of coding against the model. --- There is a contract: If you catch InterruptedException, you must either: - propagate it - or restore the flag Interruption is not about failure. It’s about control. It’s how the JVM coordinates lifecycle across threads. When you ignore it, you’re not just hiding a problem. You’re breaking the control plane of your application. Final thought Most systems don’t fail because something crashed. They fail because something refused to stop. A thread that ignores interruption is not resilient. It’s uncontrollable. And in production, uncontrollable systems don’t degrade. They hang. Then they get killed. 💬 How do you handle interruption in your production code? #Java #JVM #Multithreading #Backend #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