ホームページ  >  記事  >  Java  >  SpringBootの起動プロセスとは何ですか?

SpringBootの起動プロセスとは何ですか?

PHPz
PHPz転載
2023-05-21 23:14:548044ブラウズ

SpringBoot 起動プロセスの概要

SpringBoot アプリケーションの起動プロセスは次のステップに分割できます。

  • アプリケーション コンテキストのロード

  • アプリケーション内のすべてのコンポーネントをスキャンします

  • アプリケーション環境を自動的に構成します

  • 組み込み Web サーバーを起動します

#アプリケーション コンテキストのロード

SpringBoot アプリケーションのすべてのコンポーネントを含むコンテナーがそのコンテキストです。起動プロセス中に、SpringBoot はこのコンテナをロードして初期化します。

このステップのソース コードは、SpringApplication クラスにあります。具体的には、SpringApplication クラスの run メソッドがこのプロセスのエントリ ポイントです。このメソッドでは、Spring Boot は createApplicationContext メソッドを呼び出してアプリケーション コンテキストを作成します。

次は、createApplicationContext メソッドのソース コードです:

protected ConfigurableApplicationContext createApplicationContext() {
    Class<?> contextClass = this.applicationContextClass;
    if (contextClass == null) {
        try {
            switch (this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
                    break;
                case REACTIVE:
                    contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
                    break;
                default:
                    contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
            }
        }
        catch (ClassNotFoundException ex) {
            throw new IllegalStateException(
                    "Unable to create a default ApplicationContext, " +
                    "please specify an ApplicationContextClass", ex);
        }
    }
    return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}

このメソッドでは、SpringBoot はアプリケーションの種類 (サーブレットまたはリアクティブ) に基づいて適切なコンテキスト クラスを選択します。 )。次に、Java リフレクション メカニズムを使用してクラスをインスタンス化し、構成可能なアプリケーション コンテキスト オブジェクトを返します。

アプリケーション内のすべてのコンポーネントをスキャンする

前のステップで、SpringBoot はアプリケーション コンテキストを作成しました。この段階で、SpringBoot はアプリケーション内のすべてのコンポーネントをスキャンし、それらをアプリケーション コンテキストに登録します。

このステップのソース コードは、SpringApplication クラスの scan メソッドにあります。具体的には、このメソッドでは、SpringBoot が SpringBootBeanDefinitionScanner オブジェクトを作成し、それを使用してアプリケーション内のすべてのコンポーネントをスキャンします。

以下は scan メソッドのソース コードです:

private void scan(String... basePackages) {
    if (ObjectUtils.isEmpty(basePackages)) {
        return;
    }
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            this.includeFilters, this.excludeFilters, this.resourceLoader);
    scanner.setResourceLoader(this.resourceLoader);
    scanner.setEnvironment(this.environment);
    scanner.setIncludeAnnotationConfig(this.useAnnotatedConfig);
    scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
        @Override
        protected boolean matchClassName(String className) {
            return getExcludeClassNames().contains(className);
        }
    });
    for (String basePackage : basePackages) {
        scanner.findCandidateComponents(basePackage).forEach(this.componentDefinitions::add);
    }
}

このメソッドでは、SpringBoot は ClassPathScanningCandidateComponentProvider オブジェクトを作成し、それを使用してアプリケーション内のすべてのコンポーネントをスキャンします。このオブジェクトは、指定されたパッケージ パスにあるすべてのクラスをスキャンし、それらを Spring Bean 定義に変換します。これらの Bean 定義はアプリケーション コンテキストに登録されます。

アプリケーション環境を自動的に構成する

SpringBoot は、前の手順でアプリケーション内のすべてのコンポーネントをアプリケーション コンテキストに登録します。 SpringBoot は、データ ソース、トランザクション マネージャー、JPA 構成などのアプリケーション環境を自動的に構成します。

このステップのソース コードは、SpringApplication クラスの configureEnvironment メソッドにあります。このメソッドでは、Spring Boot は SpringApplicationRunListeners オブジェクトを作成し、それを使用してアプリケーション環境を構成します。

以下は、configureEnvironment メソッドのソース コードです。

private void configureEnvironment(ConfigurableEnvironment environment, String[] args) {
    if (this.addCommandLineProperties) {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        environment.getPropertySources().addLast(new CommandLinePropertySource(applicationArguments));
    }
    this.listeners.environmentPrepared(environment);
    if (this.logStartupInfo) {
        this.logStartupInfo(environment);
    }
    ConfigurationPropertySources.attach(environment);
    Binder.get(environment).bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(this.sources));
    if (!this.isCustomEnvironment) {
        EnvironmentConverter.configureEnvironment(environment, this.deduceEnvironmentClass());
    }
    this.listeners.environmentPrepared(environment);
}

このメソッドでは、SpringBoot は ApplicationArguments オブジェクトを作成し、それを次のように変換します。コマンドラインプロパティのソース。次に、listenersenvironmentPrepared メソッドを呼び出して、環境の準備ができたことをアプリケーションに通知します。その後、SpringBoot はプロパティ ソースをアプリケーション環境にバインドし、listenersenvironmentPrepared メソッドを呼び出して、環境の準備ができたことをアプリケーションに通知します。

組み込み Web サーバーの開始

前のステップで、SpringBoot はアプリケーション環境の構成を自動的に完了しました。このステップでは、アプリケーションが Web サービスを提供できるように、SpringBoot が組み込み Web サーバーを起動します。

このステップのソース コードは、SpringApplication クラスの run メソッドにあります。具体的には、この方法では、SpringBoot がアプリケーションの種類 (サーブレットまたはリアクティブ) に基づいて適切な組み込み Web サーバーを選択し、それを使用してアプリケーションを起動します。

次は、run メソッドのソース コードです:

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> 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;
}

このメソッドでは、SpringBoot は StopWatch オブジェクトを使用してアプリケーションを計算します。起動時間。次に、listenersstarting メソッドを呼び出して、アプリケーションが開始しようとしていることを通知します。次に、SpringBoot はアプリケーション環境を準備し、それを使用してアプリケーション コンテキストを作成します。その後、SpringBoot は listenersstarted メソッドを呼び出して、アプリケーションが開始されたことを通知します。最後に、SpringBoot は callRunners メソッドを呼び出して、すべての CommandLineRunner コンポーネントと ApplicationRunner コンポーネントを実行します。

以上がSpringBootの起動プロセスとは何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。