Spring Boot 是如何工作的?

gkn4icbw  于 7个月前  发布在  Spring
关注(0)|答案(1)|浏览(75)

我正在学习这个,我已经确定了以下步骤。

@SpringBootApplication
public class MyApplication {

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

}

字符串
1.我们运行MyApplication,它转到main方法。

SpringApplication.run(MyappApplication.class, args);

  1. SpringApplication.run(PrimaryTarget, args)此方法将调用Application上下文并返回正在运行的ApplicationContext。
    1.然后ApplicationContext扫描primaryTarget,这里是MyApplication.class的Annotations。
    1.它在MyApplication.class中看到@SpringBootApplication注解
  2. @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
  3. @EnableAutoConfiguration根据@ConditionalOnClass启动自动配置,无论类路径中是否存在JPA或Kafka类文件,如果存在则自动配置,否则不自动配置
  4. @ComponentScan在src目录中扫描类中存在的注解,如果存在,则使Bean在应用程序上下文中可用。
    这是正确的吗?如果不是,请纠正我。
t5fffqht

t5fffqht1#

大部分是正确的。
理解run方法的实现应阐明所有步骤。

public ConfigurableApplicationContext run(String... args) {
    long startTime = System.nanoTime();
    DefaultBootstrapContext bootstrapContext = this.createBootstrapContext();
    ConfigurableApplicationContext context = null;
    this.configureHeadlessProperty();
    SpringApplicationRunListeners listeners = this.getRunListeners(args);
    listeners.starting(bootstrapContext, this.mainApplicationClass);

    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments);
        this.configureIgnoreBeanInfo(environment);
        Banner printedBanner = this.printBanner(environment);
        context = this.createApplicationContext();
        context.setApplicationStartup(this.applicationStartup);
        this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
        this.refreshContext(context);
        this.afterRefresh(context, applicationArguments);
        Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
        if (this.logStartupInfo) {
            (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), timeTakenToStartup);
        }

        listeners.started(context, timeTakenToStartup);
        this.callRunners(context, applicationArguments);
    } catch (Throwable var12) {
        this.handleRunFailure(context, var12, listeners);
        throw new IllegalStateException(var12);
    }

    try {
        Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
        listeners.ready(context, timeTakenToReady);
        return context;
    } catch (Throwable var11) {
        this.handleRunFailure(context, var11, (SpringApplicationRunListeners)null);
        throw new IllegalStateException(var11);
    }
}

字符串
进一步研究

相关问题