Skip to content
javahacks.dev
Debugging

How to Debug Spring Boot With Breakpoints and Conditions

Debug a Spring Boot app from the IDE or attach to a running JVM, break only on matching requests and find out why a bean is missing.

7 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the Spring Boot, Spring, Apache Maven, OpenJDK and JUnit5 logos.

Spring Boot applications have a lot of machinery between the request and your code, and a debugger shows which parts run. The useful skills are starting the application so an IDE can attach, stopping on the right request and answering "why is this bean missing". This post covers each. The IDE basics are in debugging Java in IntelliJ IDEA, and the application is the one from Spring Boot from first project to production.

Start in debug mode

From the IDE, run the main class with the Debug button. From the command line with Maven:

Shell
./mvnw spring-boot:run -Dspring-boot.run.jvmArguments="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005"

With a packaged jar:

Shell
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar target/shop.jar

suspend=n starts the application without waiting for a debugger; suspend=y waits, which lets you debug start-up code. address=*:5005 listens on all interfaces (Java 9 and later bind to localhost only when you write 5005 alone). In the IDE, create a "Remote JVM Debug" configuration pointing at host and port, then attach. For Gradle, ./gradlew bootRun --debug-jvm does the same.

The debug port allows anyone who can connect to run code in your process. Use it on a developer machine, or over an SSH tunnel for a test server. Never open it on a public interface, and never leave the agent in production images.

Break on the right request

A breakpoint in a controller method stops for every request, including health checks. Add a condition to a breakpoint so it stops only for the one you are investigating:

Text
Condition: order.customerId().equals("c-17")

or request.getHeader("X-Debug") != null, or a hit count. Conditions are covered in conditional breakpoints and logpoints. For a failing request, an exception breakpoint on the exception class (say DataIntegrityViolationException) stops where it is thrown, deep inside the framework, with the context.

Where to put breakpoints

QuestionPlace the breakpoint
Is the controller reached?The first line of the handler method
Why did validation fail?In your @ExceptionHandler, or on MethodArgumentNotValidException
What SQL runs?Not in code: set logging.level.org.hibernate.SQL=debug instead
Which filter rejected the request?In the Spring Security filter chain with logging.level.org.springframework.security=DEBUG; a breakpoint in a custom filter
What is the request body?At the controller, or in a HandlerInterceptor.preHandle

The request path explained in how Spring MVC handles a request shows where each component sits.

Spring proxies in the call stack

Stepping into a service method may land in a generated class:

Text
dev.javahacks.OrderService$$SpringCGLIB$$0.place(<generated>)

That is the proxy that applies @Transactional and other aspects. Step Into again to reach your code, or put the breakpoint inside the method. A breakpoint on a method that is never reached usually means the call bypasses the proxy or the wrong bean is used; see how the container works.

Why is this bean missing or present?

Add --debug to the command (or debug=true in application.properties) and read the condition evaluation report at startup. It lists "Positive matches", "Negative matches" and "Unconditional classes", for example:

Text
DataSourceAutoConfiguration:
   Did not match:
      - @ConditionalOnClass did not find required class 'javax.sql.DataSource'

At runtime, the Actuator endpoint conditions shows the same, and beans lists the beans and their dependencies. Expose them in a development profile only. For a bean you expected, breakpoints inside DefaultListableBeanFactory are rarely needed; the report answers it.

Debugging tests

Debug a @SpringBootTest as you would a unit test, from the gutter icon. Context start-up dominates, so use slice tests when you can (a practical testing strategy). A failure that happens during context loading shows in the logs before any test code; see Failed to load ApplicationContext.

DevTools and class loaders

With spring-boot-devtools, the application runs in two class loaders: your classes are reloaded on change in a restart class loader. Objects from before a restart can fail casts with ClassCastException between "the same" class loaded twice. If the debugger behaves strangely after a reload, restart the application or disable DevTools restart (spring.devtools.restart.enabled=false).

A worked case: the bean that is not there

A service fails at startup with NoSuchBeanDefinitionException: No qualifying bean of type 'dev.javahacks.shop.PriceCache'. The class is annotated and in the right package, so the usual suspects are conditions. Here is a configuration that produces exactly that:

java
@Configuration
class CacheConfig {

    @Bean
    @ConditionalOnProperty(name = "shop.cache.enabled", havingValue = "true")
    PriceCache priceCache() {
        return new PriceCache(Duration.ofMinutes(5));
    }
}

The property is set in application-prod.properties and the application runs with the staging profile, so the condition is false and the bean is never created. The condition evaluation report says it directly, and you can ask for it without reading the whole startup output:

Shell
./mvnw spring-boot:run -Dspring-boot.run.arguments=--debug 2>&1 \
  | grep -A4 "CacheConfig#priceCache"
Text
CacheConfig#priceCache:
   Did not match:
      - @ConditionalOnProperty (shop.cache.enabled=true) did not find property 'shop.cache.enabled' (OnPropertyCondition)

The report names the property and the condition class. No debugger was needed, and that is the point: when the question is "why was this not created", the framework already wrote down its answer. Reach for a breakpoint when the question is about values at runtime.

Look at what the context actually holds

When a wrong bean is injected, ask the context. This runner prints every bean of a type with its source, so duplicated or unexpected definitions are visible:

java
@Component
@Profile("debug")
class BeanInspector implements ApplicationRunner {

    private final ConfigurableApplicationContext context;

    BeanInspector(ConfigurableApplicationContext context) {
        this.context = context;
    }

    @Override
    public void run(ApplicationArguments args) {
        for (String name : context.getBeanNamesForType(PriceCache.class)) {
            BeanDefinition definition = context.getBeanFactory().getBeanDefinition(name);
            System.out.printf("%s from %s (primary=%s)%n",
                name, definition.getResourceDescription(), definition.isPrimary());
        }
    }
}

Run with --spring.profiles.active=debug and read the output. Two beans of one type with neither marked @Primary explains an NoUniqueBeanDefinitionException immediately. Delete the class afterwards, or keep it behind the profile as a documented diagnostic.

Log each request without a breakpoint

For a problem that depends on what the client sent, logging the request is faster than stopping the world. Spring has a ready filter:

java
@Bean
CommonsRequestLoggingFilter requestLogging() {
    CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter();
    filter.setIncludeQueryString(true);
    filter.setIncludePayload(true);
    filter.setMaxPayloadLength(2000);
    filter.setIncludeHeaders(false);
    return filter;
}
properties
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG

Headers are excluded on purpose, because they carry tokens. Payloads can carry personal data too, so enable this in a development profile only, and keep the length cap. The alternative that needs no code is logging.level.org.springframework.web=DEBUG, which prints which handler method each request maps to, a quick answer to "is the controller even being matched".

An interceptor to break on a header

A breakpoint with a condition on a header works in the IDE, and an interceptor works on a server where you cannot attach one. This one logs a trace line only for requests carrying a debug header:

java
@Component
class DebugInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(DebugInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (request.getHeader("X-Debug-Trace") != null) {
            log.info("debug request {} {} handler={} user={}",
                request.getMethod(), request.getRequestURI(), handler,
                request.getUserPrincipal() == null ? "anonymous" : request.getUserPrincipal().getName());
        }
        return true;
    }
}

Register it in a WebMvcConfigurer. A caller adds the header on the one request being investigated, so the log stays quiet for everyone else. Guard the header behind an authority check if the application is exposed, since a header anyone can send is a way to make the server log more.

Expose the Actuator views only where you need them

The conditions, beans, env and mappings endpoints answer most "what is configured" questions at runtime, and they can leak sensitive detail, so open them narrowly:

YAML
management:
  endpoints:
    web:
      exposure:
        include: health,info,conditions,beans,mappings,configprops
  endpoint:
    configprops:
      show-values: when-authorized

Put this in a profile that only runs on developer machines or behind a protected management port. mappings lists every URL and the handler method that serves it, which settles "why does this URL return 404" faster than stepping through the dispatcher.

Where this does not apply

For timing-sensitive bugs and races, breakpoints change behavior; use logs. For production, attach tools such as jcmd and JFR instead of a debugger: using jcmd, jstack and jmap safely. The Spring Boot reference on auto-configuration describes the condition report, and the Actuator endpoints reference lists conditions and beans.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.