The Moment the Magic Breaks
It's 4:47 PM on a Thursday. You've added one more @Autowired field to a service that has worked for eighteen months, restarted the app, and the console hits you with:
You stare at the class. It has @Component on it. The package looks right. You added it the same way you've added a hundred others. Spring, which usually quietly assembles your entire application out of thin air, has decided this one bean does not exist.
This is the moment the magic breaks, and it's the moment most engineers reach for Stack Overflow instead of a mental model. The exception message is honest but unhelpful: it tells you the IoC container has no registered bean of that type1. It does not tell you why. The class might sit outside your component-scan path. The stereotype annotation might be missing or shadowed by a meta-annotation that didn't take effect. A @ConditionalOnProperty higher up the chain might have quietly excluded the entire configuration class2. Three completely different root causes, one identical stack trace.
The reason this debugging feels like guesswork is that the framework is doing two distinct jobs and most tutorials blur them together. The first job runs once, at startup: the ApplicationContext scans, instantiates, wires, and initializes every bean, then holds the result as a graph in memory1, 2. The second job runs on every HTTP call: the DispatcherServlet receives a request, picks a handler from that graph, drives it through interceptors and argument resolvers, and serializes the response3. Almost every Spring Boot bug, from a missing bean to a 415 on a perfectly valid JSON body, is a failure in one of those two pipelines. Once you can name the stage where something went wrong, the fix is usually a one-line change.
So before reaching for the next annotation to sprinkle on the class, it's worth asking: at what exact step in the lifecycle was Spring supposed to know this bean existed, and why didn't it?
What a Bean Actually Is (and How Spring Registers One)#
Strip away the annotations and the auto-configuration and you're left with a single, unglamorous idea: a bean is just a Java object whose construction you've delegated to someone else. That someone else is the Spring IoC container. It decides when the object comes into existence, what gets passed into its constructor, what callbacks fire during setup, and when it's torn down1. You wrote new exactly zero times. The container did it for you, and that handoff is the source of every "why isn't my field injected?" question on Stack Overflow.
Every dependency-managed object in a Spring application is a bean, and each one passes through the same five-stage journey: instantiated, injected, initialized, used, destroyed2. Think of the container as three things at once: a registry that knows what beans exist, a factory that builds them in the right order, and a coordinator that manages how they find each other.
Registration happens in three main ways, and the differences matter when you're debugging. A class annotated with @Component (or its stereotypes @Service, @Repository, @Controller) gets picked up by classpath scanning, provided the package falls under your @SpringBootApplication's scan root. A method annotated with @Bean inside a @Configuration class registers whatever that method returns, giving you full control over construction. Anything declared in an auto-configuration class is registered conditionally based on what's already on the classpath or in the context.
Here's the minimal version of each:
Both end up in the same place: the ApplicationContext, which is the runtime face of the IoC container. When you @Autowired a PricingService somewhere, Spring looks in this context, finds the registered singleton, and hands it over. No reflection magic at the call site, no proxy gymnastics you need to understand to read the code. Just a map lookup, give or take some scope resolution.
Web applications get a slightly richer variant called the WebApplicationContext, which extends the plain ApplicationContext by also carrying ServletContext information. The DispatcherServlet implements ApplicationContextAware precisely so it can pull this context out and use it to resolve controllers, view resolvers, and message converters at request time4. That's the bridge between the bean world and the HTTP world.
The container knows how to register and hand out beans. But in a Spring Boot application you didn't write most of these registration declarations yourself. Where did the DataSource bean come from? The ObjectMapper? The embedded Tomcat? That's the question auto-configuration answers.
Auto-Configuration: How Spring Decides What to Create#
You never wrote a @Bean method for DataSource. You never called new HikariDataSource(). Yet there it is, injected into your repository, pointing at the right URL with the right pool size. This is the part that feels like magic, and it's the part that breaks first when something on the classpath shifts.
The mechanism is mechanical, not mystical. At startup, Spring Boot scans the classpath for known libraries and classes, then consults a list of auto-configuration classes shipped inside spring-boot-autoconfigure. Each of those classes is responsible for wiring up one feature: a database connection, an embedded web server, a security filter chain, a metrics registry5. If HikariCP is on the classpath and a JDBC URL is set in your properties, DataSourceAutoConfiguration fires and registers a HikariDataSource bean. Remove the dependency and the bean quietly disappears.
The "quietly" is doing real work in that last sentence. Auto-configuration classes are not unconditional. Every bean method inside them is guarded by one or more @Conditional annotations, and the most important one is @ConditionalOnMissingBean: create this bean only if the user hasn't already registered one of the same type5. That single annotation is why auto-configuration feels like a sensible default rather than an imposition.
For the override to work, ordering matters. Spring guarantees that auto-configuration classes load after user-defined bean definitions have been registered with the context6. By the time @ConditionalOnMissingBean checks the bean factory, your custom bean is already there, and the conditional evaluates to false. Your definitions always win; defaults fill the gaps.
There is a sharp edge here. The @AutoConfiguration annotation (the newer replacement for @Configuration in starter modules) sets proxyBeanMethods = false, and under some configurations users have reported the default bean being picked over their custom one despite the documented ordering6. The contract isn't broken. How you declare your override determines whether it's actually registered before auto-configuration runs. The package it lives in, whether it's picked up by component scanning, the configuration class it sits inside: all of these affect the timing. If you've ever debugged a "my bean is being ignored" problem in a Spring Boot starter, this is usually where it lives.
The useful mental model is a two-pass registration. Pass one: your application's @Configuration classes, @Component scans, and explicit @Bean methods register their definitions. Pass two: auto-configuration classes walk their conditional checks against the context that pass one produced, filling in whatever you didn't supply. The output of both passes is a single, unified set of bean definitions, indistinguishable by origin once the context starts instantiating them. From here on, an auto-configured DataSource and a hand-written MyService travel through exactly the same lifecycle.
The Bean Lifecycle: From Instantiation to Ready#
Auto-configuration decides what should exist. The lifecycle decides how it comes into being. Between the moment Spring resolves "I need a UserService" and the moment your controller can call userService.findById(42), the container walks through a fixed sequence of stages. Skip the sequence in your head and you will burn an hour chasing a NullPointerException that the lifecycle diagram would have explained in thirty seconds.
Here is the sequence, in order, every time2, 7:
Each stage is a hook. Each hook is also a place where things can go wrong, and the wrong thing usually traces back to a misunderstanding of which stage runs when.
Instantiation is the simplest stage and the source of the most common bug. Spring calls a constructor. If you use field injection (@Autowired on a field) and then reference that field inside the constructor body, the field is still null, because field injection happens in stage 2, after the constructor has already returned2, 1. This is why constructor injection is the recommended style. The dependencies arrive as constructor arguments, so by the time the constructor body runs, they're guaranteed to be present.
Move the warmup() call to a @PostConstruct method and the problem disappears, because @PostConstruct runs in stage 5, after injection is complete.
Aware callbacks in stage 3 are something most application engineers never touch directly. If your bean implements BeanNameAware, Spring hands it the name under which it was registered. If it implements ApplicationContextAware, Spring hands it the entire context2. These are escape hatches for framework-level code. Needing ApplicationContextAware in application code is usually a sign that you're working around the DI system instead of with it.
BeanPostProcessor is the stage that explains the most apparent "magic" in Spring. A BeanPostProcessor is itself a bean, registered early, that gets to inspect and optionally replace every other bean during stages 4 and 6. The post-initialization hook is where @Transactional works: the AnnotationAwareAspectJAutoProxyCreator sees that your OrderService has @Transactional methods, wraps it in a CGLIB proxy, and returns the proxy to the container instead of your original instance2. Every other bean that gets OrderService injected actually gets the proxy. This is also why calling a @Transactional method from another method in the same class does not open a transaction: the call goes through this, bypassing the proxy entirely.
Initialization in stage 5 is where you do work that needs the bean's dependencies but should happen exactly once. The annotation form, @PostConstruct, is the common choice. The programmatic form is implementing InitializingBean and overriding afterPropertiesSet(), which Spring calls at the same point in the lifecycle7. The annotation is cleaner; the interface is useful when you're writing framework code that can't depend on javax.annotation.
Once stage 6 completes, the bean is in the container's singleton cache and ready to be injected wherever it's needed. It does its job until shutdown, at which point Spring calls @PreDestroy methods in reverse dependency order.
The diagnostic value of this sequence is concrete. When you see a NullPointerException on an injected field during startup, ask: which stage was I in when I touched that field? If it was the constructor, you touched it before stage 2 finished. If @Transactional isn't opening a transaction, you're calling a method on this instead of the stage-6 proxy. If a @PostConstruct method runs before some other bean is ready, your dependency graph is missing an edge the container can't infer.
The lifecycle covers startup. A bean that's ready in the container still has to be reached by an HTTP request, and that's a second pipeline with its own ordered stages.
Diagram as text
sequenceDiagram participant I as "Instantiation" participant D as "Dependency Injection" participant A as "Aware Interface Callbacks" participant B as "BeanPostProcessor#beforeInitialization" participant P as "@PostConstruct / afterPropertiesSet()" participant A2 as "BeanPostProcessor#afterInitialization" participant R as "Bean Ready for Use" participant D2 as "@PreDestroy / destroy()" I->>D: Create new instance D->>A: Inject dependencies A->>B: Call aware interfaces B->>P: Before initialization processing P->>A2: Post-initialization processing A2->>R: Bean is ready R->>D2: Cleanup before destroy
Bean Scopes: Singleton vs. Everything Else#
Every bean we've discussed so far has been a singleton, because singleton is what you get when you don't ask for anything else. One instance per IoC container, returned every time that bean is requested8. This default is the right default. Stateless services, repositories, configuration holders, controllers: they all share state safely because they hold no per-user, per-request state to begin with.
The trouble starts when a bean does hold state, and the developer reaches for @Scope("prototype") thinking it solves the problem.
Here is the classic bug. A RequestCounter is supposed to track something per HTTP request, so someone marks it prototype:
The counter climbs forever and is shared across every user. Prototype scope means a new instance per injection point, not per method call. The controller is a singleton. It was wired with its RequestCounter exactly once, when the context started. From that moment on, both beans live and die together, and the prototype scope has bought you nothing.
The fix is to wire in a scoped proxy that resolves to the right instance on every method call:
Now the field injected into the controller is not the counter itself but a CGLIB proxy. Each call to counter.increment() looks up the real RequestCounter bound to the current HTTP request, increments that one, and leaves nothing behind for the next request to inherit.
Spring offers other web-aware scopes for the same reason: session scope gives one instance per HTTP session for user-specific state, and prototype gives a new instance per injection point for genuinely throwaway objects. The pattern is the same in every case. A short-lived bean injected into a long-lived bean needs a proxy to mediate the lifetime mismatch.
There's a question lurking under all of this: what does "the current HTTP request" actually mean to Spring, and how does it get bound to a thread in time for the proxy to find it? Request and session scopes only make sense once you understand how a request flows through the framework. That's next.
The HTTP Request Pipeline: Tomcat to @RestController#
A curl to /api/users/42 looks instantaneous from the outside. Inside the JVM, that single request passes through at least seven distinct components before your controller method runs, and every one of them is a place where things go wrong. Trace the whole path once, thoroughly, and "the endpoint returns 404" stops being a mystery and starts being a question with an address.
Here is the route, end to end:
Stage 1: Tomcat accepts the socket. When Spring Boot starts, it embeds Tomcat as a library and binds a server socket on port 8080 by default. Tomcat parses the raw HTTP bytes into an HttpServletRequest, picks a worker thread from its pool, and hands the request to the servlet registered at /9. That servlet is the DispatcherServlet, which extends HttpServlet via FrameworkServlet and HttpServletBean4. What can fail here is mostly infrastructure: thread pool exhaustion (server.tomcat.threads.max defaults to 200, and every blocked request holds a thread), connection timeouts, and port conflicts at startup. If Tomcat itself can't accept the connection, no Spring code ever runs. Check netstat and Tomcat access logs, not Spring.
Stage 2: The FilterChain. Before the DispatcherServlet sees the request, the servlet container walks the registered Filter chain in order3. Filters live at the servlet API layer, not the Spring MVC layer, which means they run for every request including static resources and error dispatches. CORS handling, Spring Security's FilterChainProxy, request logging, and GZip compression all live here. The classic failure mode is a filter that forgets to call chain.doFilter(request, response). When that happens the request is silently swallowed3. No exception, no log line, just a hanging client or an empty 200. If your controller breakpoint never fires and no error appears, suspect a filter before you suspect anything else.
Stage 3: DispatcherServlet.doDispatch. Once the filter chain delivers control, the request enters DispatcherServlet.doDispatch(HttpServletRequest, HttpServletResponse). Knowing that method name is what makes a stack trace readable4. doDispatch does five things in order: find the handler, find an adapter for it, run pre-handle interceptors, invoke the handler, then run post-handle interceptors and resolve the view or write the response body.
Stage 4: HandlerMapping picks the controller method. The DispatcherServlet doesn't know about your @GetMapping("/users/{id}") directly. It asks each registered HandlerMapping bean whether it has a handler for this request9. The one that matters for annotated controllers is RequestMappingHandlerMapping, which scanned every @Controller and @RestController at startup and built a lookup table from (method, path-pattern, headers, params, consumes, produces) to HandlerMethod. When you get a 404 from an endpoint you're certain exists, this is the stage that rejected it. Turn on logging.level.org.springframework.web=DEBUG and you'll see exactly which HandlerMapping accepted or refused the request.
Stage 5: HandlerAdapter invokes the method. Once a handler is found, doDispatch looks for a HandlerAdapter that knows how to invoke it9. For @RequestMapping-style methods that's RequestMappingHandlerAdapter. The adapter does argument resolution: it reads @PathVariable from the URI template, @RequestParam from the query string, deserializes the request body via an HttpMessageConverter (usually Jackson) for @RequestBody, validates with @Valid, and calls your method through reflection. A @RequestParam without required=false and no default gives you a 400 the moment a client omits it. A Jackson deserialization failure on @RequestBody becomes an HttpMessageNotReadableException before your method body ever runs, which is why the controller appears innocent in the logs.
Stage 6: Controller, Service, Repository. Your @RestController method calls a @Service, which calls a @Repository, which executes SQL. Every collaborator was injected at startup, so by the time the request arrives the wiring is already done. Two failure modes to remember: self-invocation inside a service bypasses the @Transactional proxy so the inner annotation is silently ignored, and the request thread holds the database connection for the duration of the call, so slow queries cascade into Tomcat thread starvation under load.
Stage 7: Response on the way out. When your method returns, the HandlerAdapter takes the return value and runs it through an HttpMessageConverter to produce JSON, sets the Content-Type, and writes bytes to the HttpServletResponse. If anything in stages 3 through 6 threw, doDispatch consults the HandlerExceptionResolver chain instead, which is where @ControllerAdvice and @ExceptionHandler methods get their turn. The response then unwinds back through the filter chain in reverse order, and Tomcat writes the bytes to the socket.
When something goes wrong, walk the pipeline in order and ask one question at each stage: did the request reach this point? Check the Tomcat access log, then a logging filter at the top of the chain, then DEBUG on org.springframework.web, then a breakpoint in your controller. The first stage where the answer is "no" owns the bug. Bugs feel mysterious only when you're checking the wrong layer.
Diagram as text
flowchart LR A["Client"] -->|HTTP socket| B["Embedded Tomcat"] B -->|"chain.doFilter()"| C["FilterChain"] C -->|invokes method| D["DispatcherServlet"] D -->|maps URL to handler| E["HandlerMapping"] E -->|selects handler| F["HandlerAdapter"] F -->|invokes method| G["@RestController method"] G -->|logic support| H["Service Layer"] H -->|data access| I["Repository"] I -->|query data| J["Database"] J -->|returns data| I I -->|returns response| H H -->|returns to controller| G G -->|returns to dispatcher| D D -->|returns to filter| C C -->|returns response| B B -->|sends response| A
Reading Failure Signals: Diagnosing Bugs with the Mental Model#
The point of holding the whole pipeline in your head is not elegance. It's that every failure mode now has a location. When something breaks, you don't guess which annotation to try next. You ask which stage produced the symptom, and the symptom itself tells you.
Start with the easy ones. A 404 from a Spring Boot app, returned as JSON with the familiar "error": "Not Found" body, means HandlerMapping ran and found nothing to match the request path9. The request reached the front controller. The controller method did not. That narrows the cause to three possibilities: the @RequestMapping path doesn't match what you're calling, the controller class isn't registered as a bean, or the DispatcherServlet's application context never picked it up9. Hit /actuator/mappings and look for the path. If it's listed, your client is calling the wrong URL. If it's not, the controller never became a handler, and now you're debugging bean registration rather than routing.
A 401 or 403 with no log line from your controller is a different stage entirely. The request was consumed by a filter in the FilterChain before DispatcherServlet ever saw it3. A blank 200 with an empty body, when your controller swears it returns data, points to the same place: something in the filter chain wrote a response and stopped propagation3. Adding logging to your controller teaches you nothing here, because your controller never ran. Enable logging.level.org.springframework.security=DEBUG and read which filter made the decision.
A NoSuchBeanDefinitionException at startup is the lifecycle stage failing, not the request pipeline. The candidates are familiar: the bean's class isn't annotated, the package isn't scanned, a @ConditionalOnProperty excluded it, or two beans of the same type exist and neither is @Primary. A BeanCurrentlyInCreationException is a circular dependency caught mid-instantiation, and the stack trace names both ends of the cycle.
The single most useful habit is starting the app once with --debug or logging.level.org.springframework=DEBUG and reading the output5. You get the auto-configuration report showing every class that matched, every class that was excluded, and why, plus every URL-to-handler mapping printed before the first request arrives5. Most "why isn't this working" questions are answered in that log, by the application itself, before you've written a single test.
So go back to 4:47 PM on Thursday. The new @Autowired field, the failed restart, the NoSuchBeanDefinitionException. This time you don't open the file and start adding @Component annotations to see what sticks. You run:
You scroll to the CONDITIONS EVALUATION REPORT, search for the type Spring said it couldn't find, and read the line that says either "did not match" with a reason, or "matched" with the bean name that should have satisfied the injection. One of two things is true: the bean was never created and the report tells you which condition failed, or it was created under a different type or qualifier than what your field is asking for. Either way, you have the answer in the log. The next step is a one-line fix, not another hour on Stack Overflow.
Sources
- Inside Spring Boot: Managing Bean Lifecycle | by Ahmed Safwat | Mediummedium.com
- What is the Spring Bean Lifecycle? - DEV Communitydev.to
- 🌐 Journey of a Request in Spring Boot: A Deep Dive into the Full Request Lifecycle - DEV Communitydev.to
- How to get the DispatcherServlet from spring WebApplicationContext? - Stack Overflowstackoverflow.com
- Spring Boot Auto-Configuration Explained: What Happens When You Run Your App? - DEV Communitydev.to
- spring - @AutoConfiguration runs before user-defined beans - Stack Overflowstackoverflow.com
- Spring - Bean Life Cyclestutorialspoint.com
- Spring Beans Explained: Configuration, IoC Container, Scopes, and Lifecyclekamilmazurek.pl
- java - What is Dispatcher Servlet in Spring? - Stack Overflowstackoverflow.com
Keep reading
How to Scale a Spring Boot App to 1 Million Requests Per Minute
Spring Boot is a Java framework for building web services, and its out-of-the-box configuration is tuned for developer convenience, not production throughput. This article...
How Spring Security works with JWT, OAuth2, and SSO
Spring Security is a framework that intercepts every HTTP request entering your application and enforces authentication and authorization rules before that request ever reaches a...
30 Seconds of Nothing: Why Spring Boot's Startup Log Tells You Almost Nothing
You audit every @PostConstruct method. You strip out the ones doing redundant work. You rerun the app, watch the terminal, and see: Started Application in 34.2 seconds. That...