How Spring Boot Detects the Main Application Class Using StackTrace

Spring Boot determines the main application class by creating a RuntimeException, inspecting its stack trace for a method named 'main', and loading the corresponding class via Class.forName, a process illustrated with source code and a JUnit test that compares printed stack traces to the thrown exception.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
How Spring Boot Detects the Main Application Class Using StackTrace

In a follow‑up to the article "SpringBoot源码解析之应用类型识别", this piece explains how Spring Boot deduces the main application class after it has identified the application type.

The core logic resides in the deduceMainApplicationClass() method:

private Class<?> deduceMainApplicationClass() {
  try {
    StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
    for (StackTraceElement stackTraceElement : stackTrace) {
      if ("main".equals(stackTraceElement.getMethodName())) {
        return Class.forName(stackTraceElement.getClassName());
      }
    }
  } catch (ClassNotFoundException ex) {
    // Swallow and continue
  }
  return null;
}

The method works by creating a RuntimeException, retrieving its stack trace, iterating over the StackTraceElement array, and checking each element’s method name. When it finds an element whose method name equals "main", it loads that class with Class.forName. If no such element is found or the class cannot be loaded, the method returns null.

To observe this mechanism in action, a simple JUnit test is provided:

public class StackTraceTest {

  @Test
  public void testStackTrace() {
    RuntimeException exception = new RuntimeException();
    StackTraceElement[] traceElements = exception.getStackTrace();
    for (StackTraceElement element : traceElements) {
      System.out.println(element.getClassName() + ":" + element.getMethodName());
    }
    throw exception;
  }
}

The test creates a RuntimeException, prints each className:methodName pair from its stack trace, and finally re‑throws the exception.

Running the test produces two outputs. The System.out.println log shows the sequence of classes and methods that form the stack trace:

com.secbro2.learn.utils.StackTraceTest:testStackTrace
sun.reflect.NativeMethodAccessorImpl:invoke0
sun.reflect.NativeMethodAccessorImpl:invoke
sun.reflect.DelegatingMethodAccessorImpl:invoke
java.lang.reflect.Method:invoke
org.junit.runners.model.FrameworkMethod$1:runReflectiveCall
org.junit.internal.runners.model.ReflectiveCallable:run
org.junit.runners.model.FrameworkMethod:invokeExplosively
org.junit.internal.runners.statements.InvokeMethod:evaluate
org.junit.runners.ParentRunner:runLeaf
org.junit.runners.BlockJUnit4ClassRunner:runChild
org.junit.runners.BlockJUnit4ClassRunner:runChild
org.junit.runners.ParentRunner$3:run
org.junit.runners.ParentRunner$1:schedule
org.junit.runners.ParentRunner:runChildren
org.junit.runners.ParentRunner:access$000
org.junit.runners.ParentRunner$2:evaluate
org.junit.runners.ParentRunner:run
org.junit.runner.JUnitCore:run
com.intellij.junit4.JUnit4IdeaTestRunner:startRunnerWithArgs
com.intellij.rt.execution.junit.IdeaTestRunner$Repeater:startRunnerWithArgs
com.intellij.rt.execution.junit.JUnitStarter:prepareStreamsAndStart
com.intellij.rt.execution.junit.JUnitStarter:main

The exception’s own stack trace, printed by the JVM, is:

java.lang.RuntimeException
  at com.secbro2.learn.utils.StackTraceTest.testStackTrace(StackTraceTest.java:12)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  at org.junit.runners.ParentRunner$1:schedule(ParentRunner.java:71)
  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  at org.junit.runners.ParentRunner$2:evaluate(ParentRunner.java:268)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
  at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
  at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Comparing the two outputs shows identical class names, method names, and order, confirming that Spring Boot’s stack‑trace‑based detection reliably identifies the class containing the main method.

This simple yet effective technique demonstrates how Spring Boot leverages a ubiquitous debugging tool—stack traces—to perform framework‑level introspection, highlighting the value of reading source code to uncover such clever implementations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

DebuggingJavaSpringBootJUnitStackTraceMainClassDetection
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.