SpringBoot系列:2.3.2版本官方文档阅读笔记-Spring Boot Features-SpringApplication

本文记录一下SpringBoot官方文档中对SpringApplication的一些介绍。
文档链接https://docs.spring.io/spring-boot/docs/2.3.2.RELEASE/reference/htmlsingle/#boot-features-spring-application

Startup Failure

FailureAnalyzer的实现类会打印失败原因,也可以自己实现。

Lazy Initialization

SpringApplication允许Bean延迟初始化,也就是在被使用到的时候才进行创建。
SpringBoot应用开启Bean延迟初始化的方法

  • SpringApplication#setLazyInitialization
  • SpringApplicationBuilder#lazyInitialization
  • 在application.properties文件中设置spring.main.lazy-initialization=true
  • 如果想让部分Bean不延迟初始化,部分的Bean延迟初始化,那么在不需要延迟初始化的Bean上标注@Lazy(false)即可

延迟初始化的优点和缺点

  • 优点。减少应用的启动时间。
  • 缺点。如果Bean的配置有问题,那么只有等到真正使用Bean时才能发现。此外,需要确保JVM有足够的堆内存,能够装下所有的Bean实例。

Customizing SpringApplication

可以通过SpringApplication的set方法对SpringApplication进行定制,也可以通过application.properties文件(也就是外部化配置, Externalized Configuration)

public static void main(String[] args) {
    SpringApplication app = new SpringApplication(MySpringConfiguration.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
}

Fluent Builder API

SpringApplicationBuilder支持创建有层次的ApplicationContext(child ApplicationContext中必须含有Web组件,parent和child使用相同的Environment),支持Fluent Builder API。

new SpringApplicationBuilder()
        .sources(Parent.class)
        .child(Application.class)
        .bannerMode(Banner.Mode.OFF)
        .run(args);

Application Availability

ApplicationContext refresh之后,应用的状态是Liveness State
application 和 command-line runners 被调用后应用的状态是Readiness State

Application Events and Listeners

SpringFramework中定义了一些事件,SpringBoot中也定义了一些自己的事件。

An ApplicationStartingEvent is sent at the start of a run but before any processing, except for the registration of listeners and initializers.

An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known but before the context is created.

An ApplicationContextInitializedEvent is sent when the ApplicationContext is prepared and ApplicationContextInitializers have been called but before any bean definitions are loaded.

An ApplicationPreparedEvent is sent just before the refresh is started but after bean definitions have been loaded.

An ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called.

An AvailabilityChangeEvent is sent right after with LivenessState.CORRECT to indicate that the application is considered as live.

An ApplicationReadyEvent is sent after any application and command-line runners have been called.

An AvailabilityChangeEvent is sent right after with ReadinessState.ACCEPTING_TRAFFIC to indicate that the application is ready to service requests.

An ApplicationFailedEvent is sent if there is an exception on startup.

The above list only includes SpringApplicationEvents that are tied to a SpringApplication. In addition to these, the following events are also published after ApplicationPreparedEvent and before ApplicationStartedEvent:

A WebServerInitializedEvent is sent after the WebServer is ready. ServletWebServerInitializedEvent and ReactiveWebServerInitializedEvent are the servlet and reactive variants respectively.

A ContextRefreshedEvent is sent when an ApplicationContext is refreshed.

Web Environment

SpringBoot会根据classPath下的Jar包来决定ApplicationContext的具体类型,

  • 如果存在SpringMVC相关依赖,则使用AnnotationConfigServletWebServerApplicationContext
  • 如果不存在SpringMVC相关依赖并且存在SpringWebFlux相关依赖,则使用AnnotationConfigReactiveWebServerApplicationContext
  • 否则,使用AnnotationConfigApplicationContext,也就是非web类型的应用

在Junit测试中使用SpringApplication时,通常需要设置setWebApplicationType(WebApplicationType.NONE)

Accessing Application Arguments

如果需要访问传入SpringApplication.run(…​)的参数,则可以在应用中注入org.springframework.boot.ApplicationArguments

import org.springframework.boot.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

@Component
public class MyBean {

    @Autowired
    public MyBean(ApplicationArguments args) {
        boolean debug = args.containsOption("debug");
        List<String> files = args.getNonOptionArgs();
        // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]
    }

}

Using the ApplicationRunner or CommandLineRunner

如果想在SpringApplication的run方法马上要完成前执行一些代码,可以实现ApplicationRunner或CommandLineRunner接口。
如果多个Bean实现了ApplicationRunner或CommandLineRunner接口,则每个Bean可以额外实现org.springframework.core.Ordered接口或者标注org.springframework.core.annotation.Order注解来确定顺序。

import org.springframework.boot.*;
import org.springframework.stereotype.*;

@Component
public class MyBean implements CommandLineRunner {

    public void run(String... args) {
        // Do something...
    }

}

Application Exit

SpringApplication可以通过注册shutdown hook来优雅地关闭ApplicationContext,关闭过程中所有SpringFramework提供的标准的生命周期回调会被执行,例如DisposableBean接口、@PreDestroy注解以及bean的destroyMethod。
此外,也可以通过实现org.springframework.boot.ExitCodeGenerator接口,来返回一个退出码,这个退出码最终可以传递到System.exit()中。

@SpringBootApplication
public class ExitCodeApplication {

    @Bean
    public ExitCodeGenerator exitCodeGenerator() {
        return () -> 42;
    }

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

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值