Spring Boot Features

作者: 于情于你 | 来源:发表于2020-07-19 16:23 被阅读0次

1.2. Lazy Initialization

    SpringApplication允许延迟初始化应用程序。启用延迟初始化后,bean将按需要创建,而不是在应用程序启动期间创建。因此,启用延迟初始化可以减少应用程序启动所需的时间。在web应用程序中,启用延迟初始化将导致许多与web相关的bean在收到HTTP请求之前不会被初始化。

    延迟初始化的一个缺点是它会延迟发现应用程序的问题。如果延迟初始化配置错误的bean,那么在启动过程中就不会再发生故障,而问题只会在bean初始化时显现出来。还必须注意确保JVM有足够的内存来容纳应用程序的所有bean,而不仅仅是那些在启动期间初始化的bean。由于这些原因,默认情况下不会启用延迟初始化,建议在启用延迟初始化之前对JVM堆大小进行微调。

// 开启延迟初始化:
spring.main.lazy-initialization=true

    如果希望在对应用程序的其余部分使用lazy初始化时禁用某些bean的lazy初始化,可以使用@lazy(false)注解将其lazy属性显式设置为false。

1.3. Customizing the Banner

启动的banner可以通过添加一个banner.txt文件到classpath去改变。
这个文件的路径也可以通过下面的方式去指定

spring.banner.location

如果这个文件的编码不是utf8那么你可以用下面的方式去指定

spring.banner.charset

除了指定.txt文件之外你还可以指定banner.gif, banner.jpg, or banner.png

在你的banner.txt文件中你可以使用下面的占位符:

Variable Description
${application.version} 你项目的版本
${application.formatted-version} 项目的版本,格式化,比如(v1.0)
${spring-boot.version} SpringBoot的版本
${spring-boot.formatted-version} SpringBoot的版本,格式化,比如(v2.3.1.RELEASE))
${application.title} 应用的标题

    你可以使用spring.main.banner-mode属性去决定输出的模式
    System.out (console),使用已经配置的logger(log),或者根本不输出(off)

1.5. Fluent Builder API

    如果需要构建ApplicationContext层次结构(具有父/子关系的多个上下文),或者更喜欢使用“fluent”构建器API,那么可以使用SpringApplicationBuilder。
    SpringApplicationBuilder允许您将多个方法调用链接在一起,并包括父方法和子方法,这些方法允许您创建层次结构,如下例所示:

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

1.7. Application Events and Listeners

    有些事件实际上是在创建ApplicationContext之前触发的,因此不能将侦听器注册为@Bean。你可以在SpringApplication.addListeners(…)方法或SpringApplicationBuilder.listeners(…)方法。

如果你希望你的监听器自动注册,而不管应用程序的创建方式如何,你可以添加META-INF/spring.factories文件,并使用:

org.springframework.context.ApplicationListener=com.example.project.MyListener

应用程序事件在应用程序运行时按以下顺序发送:

一个ApplicationStartingEvent在运行开始时发送,但是在任何处理之前发送,初始的侦听器和注册的项除外。

当上下文中要使用的环境已知,但在创建上下文之前,将发送ApplicationEnvironmentPreparedEvent。

当准备好ApplicationContext并调用applicationContextInitializer时,但在加载任何bean定义之前,将发送一个ApplicationContextInitializedEvent。

ApplicationPreparedEvent将在刷新开始之前但在加载bean定义之后发送。

ApplicationStartedEvent将在刷新上下文之后,但在调用任何应用程序和命令行运行程序之前发送。

AvailabilityChangeEvent刚好在LivenessState.CORRECT之后发送,去表明应用程序是活动的。

在调用任何应用程序和命令行运行程序后发送ApplicationReadyEvent

AvailabilityChangeEvent 在刚好ReadinessState.ACCEPTING_TRAFFIC的时候发送,去表明应用程序可以接受请求了

ApplicationFailedEvent在启动发生异常的时候被发送

上面的列表只包括绑定到SpringApplication的SpringApplicationEvents。除此之外,还将在ApplicationPreparedEvent之后和ApplicationStartedEvent之前发布以下事件:

刷新ApplicationContext时发送ContextRefreshedEvent。
WebServerInitializedEvent在Web服务器准备就绪后发送。
ServletWebServerInitializedEvent和ReactiveWebServerInitializedEvent分别是servlet和reactive变量。

1.8. Web Environment

SpringApplication试图为你创建正确类型的ApplicationContext。用于确定WebApplicationType的算法相当简单:

    如果存在SpringMVC,AnnotationConfigServletWebServerApplicationContext就会被使用
如果Spring MVC和Spring WebFlux都存在,AnnotationConfigReactiveWebServerApplicationContext就会被使用
    否则,AnnotationConfigApplicationContext就被使用

    这意味着,如果您在同一个应用程序中使用springmvc和springwebflux的新WebClient,默认情况下将使用springmvc。您可以通过调用setWebApplicationType(WebApplicationType)轻松地覆盖它。

在使用单元测试的时候,最好调用setWebApplicationType(WebApplicationType.NONE)

1.9. 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"]
    }

}

1.10. Using the ApplicationRunner or CommandLineRunner

    如果需要在SpringApplication启动后运行某些特定代码,可以实现ApplicationRunner或CommandLineRunner接口。两个接口以相同的方式工作,并提供一个运行方法,该方法在前面被调用SpringApplication.run(…)完成。

    CommandLineRunner接口以简单的字符串数组的形式提供对应用程序参数的访问,而ApplicationRunner使用前面讨论的ApplicationArguments接口。以下示例显示了具有run方法的CommandLineRunner:

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

@Component
public class MyBean implements CommandLineRunner {

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

}

1.11. Application Exit

    每个Spring应用都向JVM注册了一个shutdown hook确保ApplicationContext优雅关闭。所有标准的Spring生命周期回调(例如DisposableBean接口或@PreDestroy注释)都可以使用。
    另外,bean可以实现org.springframework.boot.ExitCodeGenerator接口,如果他们想要返回一个特定的退出代码,当SpringApplication.exit()被调用的时候。然后可以将此退出代码传递给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)));
    }

}

2.1. Configuring Random Values

    RandomValuePropertySource用于注入随机值(例如,注入机密或测试用例中)。它可以生成整数、long、uuid或字符串,如下例所示:

my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}

2.2. Accessing Command Line Properties

    默认情况下,SpringApplication转换任何命令行选项参数(即,以--开头的参数,例如--server.port=9000)并将它们添加到Spring环境中。如前所述,命令行属性总是优先于其他属性源。

    如果不希望将命令行属性添加到环境中,可以使用SpringApplication.setAddCommandLineProperties(false)。

2.4. Profile-specific Properties

除了application.properties文件,也支持自己根据不同的环境配置不同的配置文件。命名格式如下:application-{profile}.properties.spring.profiles.active属性选择激活哪个配置文件。

2.5. Placeholders in Properties

属性支持使用占位符

app.name=MyApp
app.description=${app.name} is a Spring Boot application

2.7. Using YAML Instead of Properties

    YAML是JSON的超集,因此是一种方便的格式,用于指定分层配置数据。只要在类路径上有SnakeYAML库,SpringApplication类就会自动支持YAML作为属性的替代。
    如果您使用“Starters”,SnakeYAML由spring-boot-starter自动提供。

2.7.1. Loading YAML

    Spring框架提供了两个方便的类,可以用来加载YAML文档。YamlPropertiesFactoryBean将YAML作为属性加载,YamlMapFactoryBean将YAML作为映射加载。比如,如下的YAML文档:

environments:
    dev:
        url: https://dev.example.com
        name: Developer Setup
    prod:
        url: https://another.example.com
        name: My Cool App

上面的例子可能被翻译成如下属性:

environments.dev.url=https://dev.example.com
environments.dev.name=Developer Setup
environments.prod.url=https://another.example.com
environments.prod.name=My Cool App

相关文章

网友评论

    本文标题:Spring Boot Features

    本文链接:https://www.haomeiwen.com/subject/mmtrkktx.html