SpringApplication源码分析与作用

SpringApplication

Class that can be used to bootstrap and launch a Spring application from a Java main method. By default class will perform the following steps to bootstrap your application:

  • Create an appropriate ApplicationContext instance (depending on your classpath)
  • Register a CommandLinePropertySource to expose command line arguments as Spring properties
  • Refresh the application context, loading all singleton beans
  • Trigger any CommandLineRunner beans

可用于从Java main方法引导和启动Spring应用程序的一个类。默认情况下,类将执行以下步骤来引导您的应用程序:

  • 创建一个适当的ApplicationContext实例(取决于您的类路径)
  • 注册一个CommandLinePropertySource,将命令行参数暴露为Spring属性
  • 刷新应用程序上下文,刷新所有单例bean
  • 触发任何CommandLineRunner beans

In most circumstances the static run(Class, String[]) method can be called directly from your main method to bootstrap your application:

在大多数情况下,静态运行(类,字符串[])方法可以直接从你的主方法调用,以引导你的应用程序:

1
2
3
4
5
6
7
8
9
10
@Configuration
@EnableAutoConfiguration
public class MyApplication {
// ... Bean definitions
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

For more advanced configuration a SpringApplication instance can be created and customized before being run:

对于更高级的配置,可以在运行之前创建和定制一个SpringApplication实例:

1
2
3
4
5
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
// ... customize application settings here
application.run(args)
}

SpringApplications can read beans from a variety of different sources. It is generally recommended that a single @Configuration class is used to bootstrap your application, however, you may also set sources from:

  • The fully qualified class name to be loaded by AnnotatedBeanDefinitionReader
  • The location of an XML resource to be loaded by XmlBeanDefinitionReader, or a groovy script to be loaded by GroovyBeanDefinitionReader
  • The name of a package to be scanned by ClassPathBeanDefinitionScanner

SpringApplications可以从各种不同的来源读取bean。一般建议使用单一的@Configuration类来引导你的应用程序,但是,你也可以设置来源:

  • 由AnnotatedBeanDefinitionReader加载的完全限定类名

  • 由XmlBeanDefinitionReader加载的XML资源的位置,或由GroovyBeanDefinitionReader加载的groovy脚本的位置

  • 要被ClassPathBeanDefinitionScanner扫描的包的名称

Configuration properties are also bound to the SpringApplication. This makes it possible to set SpringApplication properties dynamically, like additional sources (“spring.main.sources” - a CSV list) the flag to indicate a web environment (“spring.main.web-application-type=none”) or the flag to switch off the banner (“spring.main.banner-mode=off”).

配置属性也绑定到SpringApplication。这使得动态设置SpringApplication属性成为可能,就像其他的资源一样(“spring.main”)。这个标志表示一个web环境(“spring.main.web-application-type=none”)或者关闭这个标志(“spring.main.banner-mode=off”)。