springboot 2.1.8官方文档翻译--3.Part IV Spring Boot features——23-SpringApplication

原文地址:https://docs.spring.io/spring-boot/docs/2.1.8.RELEASE/reference/html/boot-features.html

Table of Contents

 

Part IV. Spring Boot features

23. SpringApplication

23.1 Startup Failure

23.2 Customizing the Banner

23.3 Customizing SpringApplication

23.4 Fluent Builder API

 23.5 Application Events and Listeners

23.6 Web Environment

 23.7 Accessing Application Arguments

23.8 Using the ApplicationRunner or CommandLineRunner

23.9 Application Exit

23.10 Admin Features

 


Part IV. Spring Boot features

本节将深入讨论Spring Boot的细节。在这里,您可以了解您可能希望使用和自定义的关键特性。如果你还没有这样做,你可能想要读“第二部分”:"Part II, “Getting Started”和"Part III, “Using Spring Boot”"部分。这样你就有了很好的基础知识。

23. SpringApplication

SpringApplication类提供了一种方便的方法来引导从main()方法启动的Spring应用程序。在许多情况下,您可以委托给静态SpringApplication.run方法,如下面的示例所示:

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

当你的应用程序启动,你应该看到类似以下输出:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::   v2.1.8.RELEASE

2019-04-31 13:09:54.117  INFO 56603 --- [           main] o.s.b.s.app.SampleApplication            : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb)
2019-04-31 13:09:54.166  INFO 56603 --- [           main] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy
2019-04-01 13:09:56.912  INFO 41370 --- [           main] .t.TomcatServletWebServerFactory : Server initialized with port: 8080
2019-04-01 13:09:57.501  INFO 41370 --- [           main] o.s.b.s.app.SampleApplication            : Started SampleApplication in 2.992 seconds (JVM running for 3.658)

默认情况下,会显示信息日志消息,包括一些相关的启动细节,比如启动应用程序的用户。如果你需要一个日志级别以外的信息,你可以设置它:Section 26.4, “Log Levels”

23.1 Startup Failure

如果您的应用程序启动失败,注册的“FailureAnalyzers”将有机会提供专门的错误消息和修复问题的具体操作。例如,如果在端口8080上启动web应用程序,但是端口已经被使用了,你应该看到类似以下的信息::

***************************
APPLICATION FAILED TO START
***************************

Description:

Embedded servlet container failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
[Note]

Spring Boot provides numerous FailureAnalyzer implementations, and you can add your own.

 如果没有故障分析程序能够处理异常,您仍然可以显示完整的条件报告,以便更好地理解出错的原因。要做到这一点,对于org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener.的异常,你需要enable the debug property or enable DEBUG logging

例如,通过使用java -jar来运行你的程序,这个时候你可以使用debug来查看具体情况:

$ java -jar myproject-0.0.1-SNAPSHOT.jar --debug

23.2 Customizing the Banner

可以通过在类路径中添加一个banner.txt文件或设置spring.banner.location属性去定位文件位置。如果文件的编码不是UTF-8,可以设置spring.banner.charset。除了文本文件外,你还能增加banner.gif,banner.jpg, 或者 banner.png等图片文件或者设置spring.banner.image.location 属性来确定图片位置。而图像被转换成ASCII艺术表现形式,并打印在任何文本横幅上。

在你的banner.txt文件中,你可以使用以下任何一个占位符:

Table 23.1. Banner variables

Variable Description

${application.version}

The version number of your application, as declared in MANIFEST.MF. For example, Implementation-Version: 1.0 is printed as 1.0.

${application.formatted-version}

The version number of your application, as declared in MANIFEST.MF and formatted for display (surrounded with brackets and prefixed with v). For example (v1.0).

${spring-boot.version}

The Spring Boot version that you are using. For example 2.1.8.RELEASE.

${spring-boot.formatted-version}

The Spring Boot version that you are using, formatted for display (surrounded with brackets and prefixed with v). For example (v2.1.8.RELEASE).

${Ansi.NAME} (or ${AnsiColor.NAME}, ${AnsiBackground.NAME}, ${AnsiStyle.NAME})

Where NAME is the name of an ANSI escape code. See AnsiPropertySource for details.

${application.title}

The title of your application, as declared in MANIFEST.MF. For example Implementation-Title: MyApp is printed as MyApp.

[Tip]

通过SpringApplication.setBanner(…​)方法也能实现,使用org.springframework.boot.Banner接口和实现你自己的printBanner()方法

 你也可以使用spring.main.banner-mode属性去决定是否打印输出System.out (console),发送给log或者不打印输出。

打印出来的banner被注册为一个单例bean,名字如下:springBootBanner

[Note]

如果想要禁用,请进行如下设置:

spring:
	main:
		banner-mode: "off"

23.3 Customizing SpringApplication

SpringApplication默认设置并不是你想要的状态,你可以自定义。例如,要关掉横幅,你可以写:

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

application.properties文件来配置SpringApplication,可以去看Chapter 24, Externalized Configuration。

更加详细的可以看SpringApplication Javadoc.

23.4 Fluent Builder API

如果您需要构建一个ApplicationContext层次结构(具有父/子关系的多个上下文),或者您更喜欢使用“fluent”构建器API,你可以使用SpringApplicationBuilder。

SpringApplicationBuilder允许您将多个方法调用链接在一起,并包含允许您创建层次结构的父方法和子方法,如下面的示例所示:

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

创建ApplicationContext层次结构时存在一些限制。例如,Web组件必须包含在子上下文中,并且父上下文和子上下文都使用相同的环境。具体细节看SpringApplicationBuilder Javadoc

 23.5 Application Events and Listeners

除了通常的Spring框架事件(如ContextRefreshedEvent)之外,SpringApplication还发送一些附加的应用程序事件。

[Note]

Some events are actually triggered before the ApplicationContext is created, so you cannot register a listener on those as a @Bean. You can register them with the SpringApplication.addListeners(…​) method or the SpringApplicationBuilder.listeners(…​) method.

If you want those listeners to be registered automatically, regardless of the way the application is created, you can add a META-INF/spring.factories file to your project and reference your listener(s) by using the org.springframework.context.ApplicationListener key, as shown in the following example:

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

有些事件实际上是在创建ApplicationContext之前触发的,因此您不能将监听器注册为@Bean。 如果你想要注册他们可以通过SpringApplication.addListeners(…​)或者SpringApplicationBuilder.listeners(…​)方法。

如果你想让这些监听器自动注册,不管应用程序是如何创建的,您可以添加一个META-INF/spring.factories文件到您的项目,并通过使用org.springframework.context.ApplicationListener关键字来引用您的监听器。如下例所示:

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

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

1、ApplicationStartingEvent在运行开始时发送,这个过程却是在任何处理之前发送,而监听器和初始化器的注册除外。

2、当要在已知上下文中使用Environment但又在上下文创建之前,这个时候就会发送ApplicationEnvironmentPreparedEvent。

3、ApplicationPreparedEvent在启动刷新之前,但在加载bean定义之后发送。

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

5、在调用任何应用程序和命令行运行程序之后,将发送ApplicationReadyEvent。它表明应用程序已经准备好为请求提供服务。

6、如果启动时出现异常,则发送ApplicationFailedEvent。

[Tip]

您通常不需要使用应用程序事件,但是知道它们的存在是很方便的。在内部,Spring Boot使用事件来处理各种任务。

应用程序事件是使用Spring Framework的事件发布机制发送的。 这个机制的部分的目的是确保事件不仅发给了child上下文的监听器还发送给了ancestor上下文的监听器。因此,如果您的应用程序使用了SpringApplication实例的层次结构,一个监听器可能接收同一类型应用程序事件的多个实例。

为了让您的侦听器能够区分其上下文的事件和后代上下文的事件,它应该在请求注入它的应用程序上下文的时候,在将注入的上下文与事件的上下文进行比较。下文可以通过实现applicationcontext ware注入,如果监听器是bean,则可以通过使用@Autowired注入。

23.6 Web Environment

一个SpringApplication试图代表您创建正确类型的ApplicationContext。用于确定WebApplicationType的算法相当简单:

  • 如果存在Spring MVC,则使用AnnotationConfigServletWebServerApplicationContext。
  • 如果不存在Spring MVC,但是存在Spring WebFlux,则使用AnnotationConfigReactiveWebServerApplicationContext。
  • 其他情况下,使用AnnotationConfigApplicationContext。

这意味着如果您在同一个应用程序中使用Spring MVC和来自Spring WebFlux的新WebClient,默认情况下将使用Spring MVC。你也可以很简单的覆盖该默认的配置,通过调用setWebApplicationType(WebApplicationType)。

还可以通过调用setApplicationContextClass(…)来完全控制ApplicationContext类型。

[Tip]

在JUnit测试中使用SpringApplication时,通常需要调用setWebApplicationType(WebApplicationType.NONE)。

 23.7 Accessing Application Arguments

如果需要访问传递给SpringApplication.run(…)的应用程序参数,你可以注入org.springframework.boot.ApplicationArguments bean。ApplicationArguments接口提供对原始String[]参数、解析过的optionnon-option参数的访问,如下例所示:

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

}
[Tip]

Spring Boot也在Spring Environment注册了CommandLinePropertySource。允许让你通过使用@Value注释注入单个应用程序参数。

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

。。。一下都是英文,因为当时浏览器崩溃页面数据没有保存, 不想在打一遍了,望见谅。。。

23.8 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...
	}

}

如果定义了几个必须以特定顺序调用的CommandLineRunner或ApplicationRunner bean,则可以另外实现org.springframe .core.Ordered interface or 使用 the org.springframework.core.annotation.Order 注解。

23.9 Application Exit

每个SpringApplication向JVM注册一个关闭钩子,以确保ApplicationContext在退出时优雅地关闭。可以使用所有标准的Spring生命周期回调(例如DisposableBean接口或@PreDestroy注释)。

另外,如果它们希望在调用SpringApplication.exit()时返回特定的退出代码,bean可以实现org.springframe .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)));
	}

}

此外,ExitCodeGenerator接口可以由异常实现。当遇到这样的异常时,Spring Boot将返回实现的getExitCode()方法提供的退出代码。

23.10 Admin Features

可以通过定义spring.application.admin.enabled 属性来使用admin-related功能。

这将在MBeanServer平台上公开SpringApplicationAdminMXBean。您可以使用此功能远程管理Spring启动应用程序。这个特性对于任何服务包装器(service wrapper implementation)实现都很有用。

[Tip]

如果您想知道应用程序在哪个HTTP端口上运行,请使用local.server.port的键获取属性。.

 

发布了469 篇原创文章 · 获赞 94 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_37909508/article/details/103213611