SpringApplication类

时间:2022-06-18 06:08:52

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

  • 创建一个适当的ApplicationContext实例(取决于您的类路径)
  • 注册一个CommandLinePropertySource,将命令行参数公开为Spring属性
  • 刷新应用程序上下文,加载所有单例bean
  • 触发任何CommandLineRunner bean
  • 在大多数情况下,静态运行(类,String[])方法可以直接从你的主方法调用,以引导你的应用程序
@ configuration
@EnableAutoConfiguration
public class MyApplication {
    //……Bean的定义
    public static void main(String[] args) {
        SpringApplication.run (MyApplication.class, args);
    }
}

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

public static void main(String[] args) {
    SpringApplication application = new SpringApplication(MyApplication.class);
    //……在这里自定义应用程序设置
    application.run (args)
}

spring应用程序可以从各种不同的来源读取bean。一般建议使用单一的@Configuration类来引导应用程序,不过,您也可以从:

  • 由带注释的beandefinitionreader加载的完全限定类名
  • 由XmlBeanDefinitionReader加载的XML资源的位置,或由GroovyBeanDefinitionReader加载的groovy脚本的位置
  • 要由ClassPathBeanDefinitionScanner扫描的包的名称
  • 配置属性也绑定到spring应用程序。这使得动态设置SpringApplication属性成为可能,比如附加的源(“spring.main”)。这个标志表示一个web环境(“spring.main.web-application-type=none”)或者关闭这个横幅(“spring.main.banner-mode=off”)。