Backend Development 8 min read

Understanding the Spring Boot Startup Process and Auto‑Configuration Mechanism

This article walks through the complete Spring Boot startup sequence, illustrating the entry point, the internal run method, environment preparation, context creation, bean factory processing, and final refresh steps, while highlighting the role of auto‑configuration and providing annotated code examples.

政采云技术
政采云技术
政采云技术
Understanding the Spring Boot Startup Process and Auto‑Configuration Mechanism

Spring Boot Startup Flow Overview

The article uses a real Spring Boot application as a case study to dissect the startup logic and auto‑configuration principles, referencing class diagrams and flowcharts.

1. Spring Boot Startup Entry

@EnableScheduling
@EnableAsync
@SpringBootApplication
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {
    "cn.gov.zcy.demand",
    "cn.gov.zcy.id.util",
    "cn.gov.zcy.backlog.sdk",
    "com.dtdream.vanyar",
    "cn.gov.zcy.base.server.gateway",
    "cn.gov.zcy.workflow.sdk"
})
@ImportResource(value = "classpath:/spring/*.xml")
@MapperScan(basePackages = {"cn.gov.zcy.demand.dao", "cn.gov.zcy.workflow.sdk.dao", "cn.gov.zcy.springboot.workflow.core"})
@ImportAutoConfiguration(value = {ExternalAutoConfiguration.class})
public class CenterApplication {
    public static void main(String[] args) {
        SpringApplication.run(CenterApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    @Bean
    public WorkflowSdkConfig workflowSdkConfig(){
        WorkflowSdkConfig config = new WorkflowSdkConfig();
        config.defaultTaskLogComp(Boolean.FALSE);
        config.defaultTimelineComp(Boolean.FALSE);
        return config;
    }
}

2. Core Run Method Execution

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection
exceptionReporters = new ArrayList<>();
    configureHeadlessProperty();
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        configureIgnoreBeanInfo(environment);
        Banner printedBanner = printBanner(environment);
        context = createApplicationContext();
        exceptionReporters = getSpringFactoriesInstances(
            SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context);
        prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        refreshContext(context);
        afterRefresh(context, applicationArguments);
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass)
                .logStarted(getApplicationLog(), stopWatch);
        }
        listeners.started(context);
        callRunners(context, applicationArguments);
    } catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }
    try {
        listeners.running(context);
    } catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }
    return context;
}

3. SpringApplication Constructor

@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class
... primarySources) {
    this.resourceLoader = resourceLoader;
    Assert.notNull(primarySources, "PrimarySources must not be null");
    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    this.webApplicationType = deduceWebApplicationType();
    setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    this.mainApplicationClass = deduceMainApplicationClass();
}

4. ApplicationContext Refresh Process

public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        prepareRefresh();
        // Tell the subclass to refresh the internal bean factory.
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
        // Prepare the bean factory for use in this context.
        prepareBeanFactory(beanFactory);
        try {
            // Allows post-processing of the bean factory in context subclasses.
            postProcessBeanFactory(beanFactory);
            // Invoke factory processors registered as beans in the context.
            invokeBeanFactoryPostProcessors(beanFactory);
            // Register bean processors that intercept bean creation.
            registerBeanPostProcessors(beanFactory);
            // Initialize message source for this context.
            initMessageSource();
            // Initialize event multicaster for this context.
            initApplicationEventMulticaster();
            // Initialize other special beans in specific context subclasses.
            onRefresh();
            // Check for listener beans and register them.
            registerListeners();
            // Instantiate all remaining (non-lazy-init) singletons.
            finishBeanFactoryInitialization(beanFactory);
            // Last step: publish corresponding event.
            finishRefresh();
        } catch (BeansException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Exception encountered during context initialization - " +
                    "cancelling refresh attempt: " + ex);
            }
            // Destroy already created singletons to avoid dangling resources.
            destroyBeans();
            // Reset 'active' flag.
            cancelRefresh(ex);
            // Propagate exception to caller.
            throw ex;
        } finally {
            // Reset common introspection caches in Spring's core.
            resetCommonCaches();
        }
    }
}

5. Subsequent Steps

After the context is refreshed, Spring Boot looks for CommandLineRunner and ApplicationRunner beans and executes them, then invokes the finished() method of all SpringApplicationRunListener instances, handling any exceptions that may have occurred.

The article also includes numerous flowcharts illustrating each step, such as environment preparation, listener notifications, banner printing, context creation, bean factory post‑processing, and final bean instantiation.

Reference: Spring Boot Startup Process Documentation

backendJavaSpringBootstartupAuto‑ConfigurationApplicationContext
政采云技术
Written by

政采云技术

ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.

0 followers
Reader feedback

How this landed with the community

login 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.