Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 11

Debugging Spring Startup with Breakpoints

This lesson is built with resources from youtube.com, javacodegeeks.com and 1 more site.

Hello! In our last lesson, we successfully wired our BlogService and BlogRepository together using constructor injection. We also saw our first major Spring error, NoSuchBeanDefinitionException, when we deliberately removed the @Repository annotation. That error was a clue: Spring couldn't find the bean it needed.

This lesson dives into the "why" behind that. We'll investigate two fundamental startup processes:

  1. Component Scanning: How does Spring know which classes to turn into beans in the first place?
  2. Bean Lifecycle: What are the exact steps a bean goes through from the moment it's just a class on your disk to a fully-functional object ready to serve requests?

Our goal is to use the debugger to trace these processes live, peeling back the "magic" of Spring Boot's startup. This is a crucial skill for diagnosing complex startup failures and understanding the framework's internal workings.

1. How Spring Discovers Your Beans: Component Scanning

When your application starts, Spring needs to find all the classes you've marked with stereotype annotations like @Component, @Service, @Repository, and @Controller. This discovery process is called component scanning.

By default, Spring doesn't scan your entire classpath. That would be inefficient. Instead, it follows a convention.

Spring Boot Component Scanning Default Behavior
This diagram shows Spring Boot's default component scanning behavior. It automatically scans the package where your main application class (annotated with `@SpringBootApplication`) is located, along with all of its sub-packages. Any packages outside this hierarchy are ignored by default.

The @SpringBootApplication annotation is a composite annotation that includes @ComponentScan. It's this @ComponentScan that tells Spring to start its search from the main class's package.

MERN Stack Comparison

This is very similar to the "convention over configuration" principle in frameworks like Next.js. Next.js automatically creates routes from files you place in the /app or /pages directory. You don't manually register each route. Similarly, Spring automatically discovers components you place in the correct packages. This is a contrast to a basic Express app where you often have to import each router and app.use() it explicitly.


2. Hands-On: Breaking and Fixing Component Scanning

Let's prove this scanning rule with an experiment. We'll create a component outside the scannable area and watch the application fail.

Task 1: Create an "Unscannable" Component

  1. In your src/main/java directory, create a new package at the same level as com.blogplatform.blogplatform. Let's name it com.blogplatform.util.

  2. Inside this new util package, create a class named UnscannableComponent.java.

    package com.blogplatform.util;
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class UnscannableComponent {
        public UnscannableComponent() {
            System.out.println("UnscannableComponent has been created!");
        }
    }
    
  3. Now, try to inject this component into your TestController.java.

    // In TestController.java
    package com.blogplatform.blogplatform.controller;
    
    import com.blogplatform.blogplatform.service.BlogService;
    import com.blogplatform.util.UnscannableComponent; // Import the new component
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class TestController {
    
        private final BlogService blogService;
        private final UnscannableComponent unscannableComponent; // Add this field
    
        // Modify the constructor
        public TestController(BlogService blogService, UnscannableComponent unscannableComponent) {
            this.blogService = blogService;
            this.unscannableComponent = unscannableComponent;
        }
    
        // ... rest of the class
    }
    
  4. Run the application. It will fail with the familiar NoSuchBeanDefinitionException. The error message will tell you that it couldn't find a bean of type UnscannableComponent when trying to create the TestController. Even though it's marked with @Component, it's in a location Spring doesn't look at by default.

Task 2: Fixing the Scan Path

There are two ways to fix this.

Option 1 (The Recommended Way): Keep components within the hierarchy.
Move the com.blogplatform.util package inside com.blogplatform.blogplatform, making it com.blogplatform.blogplatform.util. Rerun the app, and it will start successfully. This adheres to the standard project structure.

Option 2 (For specific use-cases): Explicitly define scan packages.
If you must keep packages separate (e.g., in a multi-module project), you can tell Spring exactly where to look.

// In BlogPlatformApplication.java
package com.blogplatform.blogplatform;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
// Tell Spring to scan both the default package AND our new util package
@ComponentScan(basePackages = {"com.blogplatform.blogplatform", "com.blogplatform.util"})
public class BlogPlatformApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlogPlatformApplication.class, args);
    }

}

This overrides the default behavior. Undo this change and revert to Option 1 for the rest of our course to stick to convention.

To see a detailed demonstration of these component scanning rules and how to configure them, the following video is excellent.

Mastering Spring @ComponentScan Annotation: Deep Dive with Examples

The video 'Mastering Spring @ComponentScan Annotation' provides a great visual and code-based explanation of how component scanning works, including how to debug it when beans aren't found.

Watch from 05:30 to 09:16 to see how the @SpringBootApplication annotation implies component scanning. Then, watch from 12:19 to 16:28, where the presenter demonstrates exactly what we just did: creating a bean in an outside package, seeing it fail, and then fixing it by explicitly defining the basePackages.


3. The Spring Bean Lifecycle

Simply finding and creating an object isn't the whole story. Spring manages a sophisticated lifecycle for each bean. Understanding these lifecycle phases is key to knowing when and where to place custom initialization or cleanup logic.

Spring Bean Life Cycle Diagram
This flowchart details the Spring Bean Lifecycle. Don't be intimidated by the number of steps. For now, focus on the main path: **Instantiate** -> **Populate Properties (Inject Dependencies)** -> **Initialization Callbacks (like `@PostConstruct`)** -> Bean is Ready -> **Destruction Callbacks (like `@PreDestroy`)**.

MERN Stack Comparison

In Node.js, an object's lifecycle is typically constructor runs -> object is used -> garbage collected. Spring provides explicit hooks that are more like the lifecycle methods in a React component.

  • @PostConstruct is analogous to useEffect(() => { ... }, []) in a React functional component. It runs once after the component has been created and all its dependencies (props) have been injected, making it a safe place to perform initialization logic that relies on those dependencies.
  • @PreDestroy is analogous to the cleanup function returned from useEffect. It runs just before the component is removed, allowing you to release resources (e.g., close a network connection).

4. Runtime Investigation: Debugging the Startup Sequence

Now, let's become archeologists of our application's startup. We will place breakpoints deep inside the Spring framework's code to see these lifecycle events unfold.

This video will be our guide as we step through the run method.

How Spring Boot Application Internally Works | Let's Debug and Understand run() Method Step by Step

The video 'How Spring Boot Application Internally Works' from Java Guides does exactly what we want to do: it debugs the SpringApplication.run() method to uncover the startup sequence.

Watch from 04:08 to 16:05. The goal is not to memorize every line, but to follow the debugging journey and understand the key phases: preparing the environment, creating the application context (the IoC container), refreshing the context (where beans are created), and calling runners.

Task 3: Follow the White Rabbit (Debug SpringApplication.run)

  1. Set Initial Breakpoint: Go to your BlogPlatformApplication.java's main method. Place a breakpoint on the line SpringApplication.run(BlogPlatformApplication.class, args);.
  2. Start Debugging: Run the application in Debug Mode (Shift+F9 in IntelliJ).
  3. Step Into: When the breakpoint hits, press the "Step Into" (F7) button. You'll jump into the SpringApplication.run static method. Step into the next run method. You should now be in a large run method with a try...finally block. This is the heart of the startup process.
  4. Observe Key Steps: Use "Step Over" (F8) to walk through the method. You will see lines corresponding to the steps mentioned in the video:
    • stopwatch.start(): Spring times its own startup.
    • getRunListeners() and listeners.starting(): Event listeners are prepared.
    • prepareEnvironment(): Application properties are loaded.
    • printBanner(): The Spring Boot ASCII art banner is printed.
    • createApplicationContext(): Crucial step! This is where the IoC container itself is instantiated. Step into this method briefly to see it determine the context type (it will be a Servlet type because we have the spring-boot-starter-web dependency).
    • refreshContext(context): This is the main event! This single method call triggers the entire component scanning and bean creation process. We won't step into this method as it's enormous, but this is where all the lifecycle magic happens.
    • afterRefresh(context, applicationArguments): A hook after the context is ready.
    • listeners.started(context): Notifies listeners the context is ready.
    • callRunners(context, applicationArguments): Executes any ApplicationRunner or CommandLineRunner beans.
    • listeners.running(context): Notifies listeners the application is fully running.

By stepping through this, you are watching the exact sequence Spring follows to launch your application.

Task 4: Observing a Single Bean's Lifecycle

Let's zoom in on one of our beans, BlogService, and verify its lifecycle.

  1. Add a @PostConstruct method to BlogService.java. This annotation comes from javax.annotation (or jakarta.annotation in newer Spring versions).

    // In BlogService.java
    import javax.annotation.PostConstruct; // Add this import
    
    @Service
    public class BlogService {
        // ... constructor and field ...
    
        @PostConstruct
        public void init() {
            System.out.println("BlogService @PostConstruct: This method is called after dependencies are injected.");
            // You can safely use blogRepository here
            System.out.println("Repository class: " + blogRepository.getClass().getName());
        }
    
        // ... getRepositoryData() method ...
    }
    
  2. Set a breakpoint inside the BlogService constructor and another inside the new init() method.

  3. Run in Debug Mode.

  4. Observation: The debugger will stop at the constructor first. The blogRepository field is being assigned. Then, press "Resume Program" (F9). The debugger will then stop at the @PostConstruct method. This proves the lifecycle order: Spring instantiates the object and injects its dependencies before calling the initialization callbacks.


5. Verifying Loaded Beans with Actuator

Debugging is powerful, but sometimes you just want a quick list of what's currently in the IoC container. Spring Boot Actuator provides a web endpoint for exactly this.

First, you need to add the Actuator dependency to your pom.xml.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Next, you need to expose the beans endpoint. Add the following to your src/main/resources/application.properties file:

management.endpoints.web.exposure.include=health,info,beans

Now, restart your application. You can access http://localhost:8080/actuator/beans in your browser or Postman. You will get a large JSON response detailing every single bean that Spring has created and managed, including yours (blogService, blogRepository, testController) and many internal ones.

Spring Boot Debugging with IntelliJ - Java Code Geeks

The article 'Spring Boot Debugging with IntelliJ' provides a great summary of how to use Actuator to inspect beans at runtime.

Read section 3, 'Viewing Loaded Beans at Runtime,' and its subsection 3.3, 'Why This Matters?'. It explains how to use both IntelliJ's built-in tools and the Actuator endpoint we just enabled to verify that your beans are being correctly picked up by component scanning.


Conclusion

Today, you've gone from a user of the Spring IoC container to an investigator of its internal mechanics. This is a significant step towards deep expertise.

Key Takeaways:

  • Component Scanning is how Spring discovers your beans, starting from the main application class's package and its sub-packages.
  • The Bean Lifecycle is a well-defined sequence of events, including instantiation, dependency injection, and initialization/destruction callbacks.
  • @PostConstruct is the standard annotation for running logic after a bean's dependencies are injected.
  • You can use the debugger to step through the SpringApplication.run method and watch the framework bootstrap itself.
  • Spring Boot Actuator's /beans endpoint gives you a runtime snapshot of every bean in the IoC container.

Preview of the next lesson:
We've now seen how Spring finds and creates beans, but often, the behavior of these beans needs to be configured externally without changing the code. For example, you wouldn't want to hardcode a database URL. In the next lesson, we will explore application.properties and the more powerful YAML format (application.yml) to manage application configuration. We'll also introduce Spring Profiles, allowing us to maintain different configurations for different environments like dev, staging, and prod.