SpringApplication.run(*.class, args)中的*.class参数的目的是什么?

5
在Sprint Boot中,Spring应用程序通过在main方法中调用SpringApplication.run(*.class, args)来初始化。我想知道在run方法中传入*.class引用的目的是什么?
经过查看源代码后(source code),这个问题并不立即显而易见,我不确定为什么需要它。
package org.java.simpleapp.simpleapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SimpleApplication {

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

}
1个回答

1
通过启动Application类,我们可以完成一系列操作,例如Spring初始化、自动装配等。启动过程有两个入口点:@SpringBootApplicationSpringApplication.run

1.入口方法:

静态帮助程序,可以使用默认设置从指定源运行SpringApplication。primarySource是要加载的主要源,args是应用程序参数(通常从Java main方法传递),这将导致运行ApplicationContext。

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
    return run(new Class<?>[] { primarySource }, args);
}

在调用静态 run 方法之后,通过一系列的调用,我们最终会进入 Spring Application 类中的以下位置。
正如您所看到的,这个方法做了两件事情,初始化 Spring Application 类并调用内部的公共 run 方法。

2. Spring应用程序初始化

运行Spring应用程序,创建并刷新一个新的ApplicationContext应用上下文, 使用参数args是应用程序参数(通常从Java main方法传递),返回一个运行中的 ApplicationContext。

public ConfigurableApplicationContext run(String... args) {

      ...

      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);
        }

      ...

}

run()方法负责管理上下文、环境、监听器、应用程序参数和打印的横幅,正如我们在中看到的那样。

prepareContext(context, environment, listeners, applicationArguments, printedBanner);

你可能想要在这里探索更多细节 启动流程源码分析

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接