Spring Boot 2.0.0参考手册_中英文对照_Part IV_23

字数 3331阅读 148

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

Part IV. Spring Boot features

This section dives into the details of Spring Boot. Here you can learn about the key features that you will want to use and customize. If you haven’t already, you might want to read the Part II, “Getting started” and Part III, “Using Spring Boot” sections so that you have a good grounding of the basics.

这一部分进入Spring Boot细节部分。在这部分你会了解到你想使用和定制的一些重要特性。如果你还没准备好,你可以阅读第二部分“Getting started”和第三部分“Using Spring Boot”,可以对基础知识有个较好的认识。

23. SpringApplication

The SpringApplication class provides a convenient way to bootstrap a Spring application that will be started from a main() method. In many situations you can just delegate to the static SpringApplication.run method:

SpringApplication提供了一种很方便的方式来引导Spring应用,Spring应用可以从main()方法中启动。许多情况下你可以委托给静态方法SpringApplication.run

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

When your application starts you should see something similar to the following:

当你的应用启动时你应该看到类似于下面的东西:

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

2013-07-31 00:08:16.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)
2013-07-31 00:08:16.166  INFO 56603 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy
2014-03-04 13:09:54.912  INFO 41370 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2014-03-04 13:09:56.501  INFO 41370 --- [           main] o.s.b.s.app.SampleApplication            : Started SampleApplication in 2.992 seconds (JVM running for 3.658)

By default INFO logging messages will be shown, including some relevant startup details such as the user that launched the application.

默认情况下会输出INFO日志信息,包括一些相关的启动细节例如启动应用的用户。

23.1 Startup failure

If your application fails to start, registered FailureAnalyzers get a chance to provide a dedicated error message and a concrete action to fix the problem. For instance if you start a web application on port 8080 and that port is already in use, you should see something similar to the following:

如果你的应用启动失败,注册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.

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

 

Spring Boot提供了许多FailureAnalyzer实现,你可以很容易添加自己的FailureAnalyzer实现。

If no failure analyzers are able to handle the exception, you can still display the full auto-configuration report to better understand what went wrong. To do so you need to enable the debug property or enable DEBUG logging for org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer.

如果没有失败分析器能处理这个异常,你仍可以显示完整的自动配置报告,从而更好的理解什么地方出问题了。为了实现这个你需要启用debug属性或启用org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializerDEBUG日志。

For instance, if you are running your application using java -jar you can enable the debug property as follows:

例如,如果你使用java -jar运行应用,你可以用下面的形式启用debug属性:

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

23.2 Customizing the Banner

The banner that is printed on start up can be changed by adding a banner.txt file to your classpath, or by setting banner.location to the location of such a file. If the file has an unusual encoding you can set banner.charset (default is UTF-8). In addition to a text file, you can also add a banner.gif, banner.jpg or banner.png image file to your classpath, or set a banner.image.location property. Images will be converted into an ASCII art representation and printed above any text banner.

启动时打印的标语可以通过在classpath中添加一个banner.txt文件或者将banner.location设置为banner.txt文件的位置来修改。如果文件是一种不常见的编码方式,你可以设置banner.charset(默认是UTF-8)。除了文本文件之外,你也添加一个banner.gifbanner.jpgbanner.png图像文件到classpath中,或者设置一个banner.image.location属性。图像将被转换成ASCII艺术表示并打印在文本标语之上。

Inside your banner.txt file you can use any of the following placeholders:

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 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 1.4.2.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 (v1.4.2.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.

Table 23.1. Banner变量

Variable Description
${application.version} 你的应用的版本号在MANIFEST.MF中声明。 例如Implementation-Version: 1.0打印成1.0.
${application.formatted-version} MANIFEST.MF中的声明的应用版本号进行格式化显示(加上前缀v并用括号包裹)。例如(v1.0)
${spring-boot.version} 你使用的Spring Boot版本。例如1.4.2.RELEASE.
${spring-boot.formatted-version} 你使用的Spring Boot版本进行格式化显示加上前缀v并用括号包裹)。例如(v1.4.2.RELEASE)
${Ansi.NAME} (or ${AnsiColor.NAME}, ${AnsiBackground.NAME}, ${AnsiStyle.NAME}) NAME是ANSI转义码的名字。更多细节请看AnsiPropertySource
${application.title} MANIFEST.MF中声明的应用标题。例如Implementation-Title: MyApp打印成MyApp.

The SpringApplication.setBanner(…​) method can be used if you want to generate a banner programmatically. Use the org.springframework.boot.Banner interface and implement your own printBanner() method.

 

如果你想自动生成一个标语你可以使用SpringApplication.setBanner(…​)方法。使用org.springframework.boot.Banner接口并实现你自己的printBanner()方法。

You can also use the spring.main.banner-mode property to determine if the banner has to be printed on (console), using the configured logger (log) or not at all (off).

你也可以使用spring.main.banner-mode属性来决定标语是否必须在System.out(控制台)上输出,使用配置的日志(log)或一点也不用(off)。

The printed banner will be registered as a singleton bean under the name pringBootBanner.

输出的banner会注册名字为pringBootBanner的单例bean。

YAML maps off to false so make sure to add quotes if you want to disable the banner in your application.

spring:
    main:
        banner-mode: "off"

 

如果你想在你的应用中禁用banner,YAML会将off映射为false,因此要确保添加引用。

spring:
    main:
        banner-mode: "off"

23.3 Customizing SpringApplication

If the SpringApplication defaults aren’t to your taste you can instead create a local instance and customize it. For example, to turn off the banner you would write:

如果你不喜欢默认的SpringApplication,你可以创建一个本地实例并定制它。例如,关闭你写的banner:

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

The constructor arguments passed to SpringApplication are configuration sources for spring beans. In most cases these will be references to @Configuration classes, but they could also be references to XML configuration or to packages that should be scanned.

 

传给SpringApplication的构造函数参数是Spring beans配置源。在大多数情况下将会引用@Configuration类,但它们也可以引用XML配置或应该扫描的包。

It is also possible to configure the SpringApplication using an application.properties file. See Chapter 24, Externalized Configuration for details.

也可以使用application.properties文件配置SpringApplication。更多细节请看24章,『外部配置』。

For a complete list of the configuration options, see the SpringApplication Javadoc.

完整的配置选项列表,请看SpringApplication文档。

23.4 Fluent builder API

If you need to build an ApplicationContext hierarchy (multiple contexts with a parent/child relationship), or if you just prefer using a fluent builder API, you can use the SpringApplicationBuilder.

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

The SpringApplicationBuilder allows you to chain together multiple method calls, and includes parent and child methods that allow you to create a hierarchy.

SpringApplicationBuilder允许你链接多个方法调用,包括允许你创建分层的parentchild方法。

For example:

例如:

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

There are some restrictions when creating an ApplicationContext hierarchy, e.g. Web components must be contained within the child context, and the same Environment will be used for both parent and child contexts. See the SpringApplicationBuilder Javadoc for full details.

 

当创建ApplicationContext分层时有一些限制,例如,子上下文必须包含web组件,父子上下文将使用同一个Environment。更完整的细节请看SpringApplicationBuilder文档。

23.5 Application events and listeners

In addition to the usual Spring Framework events, such as ContextRefreshedEvent, a SpringApplication sends some additional application events.

除了平常的Spring框架事件之外,例如ContextRefreshedEventSpringApplication会发送一些其它的应用事件。

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 via the SpringApplication.addListeners(…​) or SpringApplicationBuilder.listeners(…​) methods.

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) using the org.springframework.context.ApplicationListener key.

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

 

ApplicationContext创建之前实际上会触发一些事件,因此你不能使用@Bean来注册这些监听器。你可以通过SpringApplication.addListeners(…​)SpringApplicationBuilder.listeners(…​)方法来注册这些监听器。

如果你想自动注册这些监听器,不管上下文的创建方式,你可以在你的工程中添加META-INF/spring.factories文件,并通过org.springframework.context.ApplicationListener作为key来引用你的监听器。

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

Application events are sent in the following order, as your application runs:

  1. An ApplicationStartedEvent, but before any processing except the registration of listeners and initializers.
  2. An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context is created.
  3. An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.
  4. An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests.
  5. An ApplicationFailedEvent is sent if there is an exception on startup.

当你的应用运行时,应用事件以下面的顺序发送:

  1. 在运行启动时发送ApplicationStartedEvent,除了监听器和初始化器注册之外,在进行任何处理之前发送。
  2. 当在上下文中使用的Environment已知时,发送ApplicationEnvironmentPreparedEvent,但发送是在上下文创建之前。
  3. 在再刷新启动之前,但在bean定义加载之后,发送ApplicationPreparedEvent
  4. 在再刷新之后,发送ApplicationReadyEvent,任何相关的回调函数都处理完成之后,意味着应用已经准备处理服务请求了。
  5. 如果启动时出现异常,发送ApplicationFailedEvent.

You often won’t need to use application events, but it can be handy to know that they exist. Internally, Spring Boot uses events to handle a variety of tasks.

 

经常你不需要使用应用事件,但知道它们的存在是便利的。Spring Boot内部使用事件来处理大量的任务。

23.6 Web environment

A SpringApplication will attempt to create the right type of ApplicationContext on your behalf. By default, an AnnotationConfigApplicationContext or AnnotationConfigEmbeddedWebApplicationContext will be used, depending on whether you are developing a web application or not.

SpringApplication会尝试创建代表你的合适的ApplicationContext类型。默认情况下,会使用AnnotationConfigApplicationContextAnnotationConfigEmbeddedWebApplicationContext,依赖于你是否在开发一个web应用。

The algorithm used to determine a ‘web environment’ is fairly simplistic (based on the presence of a few classes). You can use setWebEnvironment(boolean webEnvironment) if you need to override the default.

使用的决定web environment的算法是相对简单的(基于现有的一些类)。如果你需要覆写默认值你可以使用setWebEnvironment(boolean webEnvironment)

It is also possible to take complete control of the ApplicationContext type that will be used by calling setApplicationContextClass(…​).

完全控制ApplicationContext类型也是可能的,通过调用setApplicationContextClass(…​)使用。

It is often desirable to call setWebEnvironment(false) when using SpringApplication within a JUnit test.

 

当在JUnit测试时使用SpringApplication,经常需要调用setWebEnvironment(false)

23.7 Accessing application arguments

If you need to access the application arguments that were passed to SpringApplication.run(…​) you can inject a org.springframework.boot.ApplicationArguments bean. The ApplicationArguments interface provides access to both the raw String[] arguments as well as parsed option and non-option 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"]
    }

}

Spring Boot will also register a CommandLinePropertySource with the Spring Environment. This allows you to also inject single application arguments using the @Value annotation.

 

Spring Boot也在Spring Environment中注册CommandLinePropertySource。这也允许你使用@Value注解注入单个应对参数。

23.8 Using the ApplicationRunner or CommandLineRunner

If you need to run some specific code once the SpringApplication has started, you can implement the ApplicationRunner or CommandLineRunner interfaces. Both interfaces work in the same way and offer a single run method which will be called just before SpringApplication.run(…​) completes.

如果你需要在SpringApplication启动时运行一些特定的代码,你可以实现ApplicationRunnerCommandLineRunner接口。这两个接口以同样方式工作,并有一个单独的run方法,在SpringApplication.run(…​)之前会调用这个run方法。

The CommandLineRunner interfaces provides access to application arguments as a simple string array, whereas the ApplicationRunner uses the ApplicationArguments interface discussed above.

CommandLineRunner接口提供了对应用参数的访问,应用参数作为一个简单的字符串数组,而ApplicationRunner使用前面描述的ApplicationArguments接口。

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

@Component
public class MyBean implements CommandLineRunner {

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

}

You can additionally implement the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation if several CommandLineRunner or ApplicationRunner beans are defined that must be called in a specific order.

另外,如果定义的CommandLineRunnerApplicationRunner beans必须以指定顺序调用,你可以实现org.springframework.core.Ordered接口或org.springframework.core.annotation.Order 注解。

23.9 Application exit

Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used.

为了确保ApplicationContext在关闭时安全退出, 每个SpringApplication都会在JVM中注册一个关闭钩子。所有的标准Spring生命周期回调函数(例如DisposableBean接口,或@PreDestroy注解)都会被使用。

In addition, beans may implement the org.springframework.boot.ExitCodeGenerator interface if they wish to return a specific exit code when the application ends.

另外,当应用退出时,如果想返回一个指定的退出码,beans可以实现org.springframework.boot.ExitCodeGenerator接口。

23.10 Admin features

It is possible to enable admin-related features for the application by specifying the spring.application.admin.enabled property. This exposes the SpringApplicationAdminMXBean on the platform MBeanServer. You could use this feature to administer your Spring Boot application remotely. This could also be useful for any service wrapper implementation.

如果应用想启用admin相关的功能,可以指定spring.application.admin.enabled属性。这会在平台MBeanServer上暴露SpringApplicationAdminMXBean。你可以使用这个功能远程的管理你的Spring Boot应用。对于任何服务包裹的实现这是很有用的。

If you want to know on which HTTP port the application is running, get the property with key local.server.port.

 

如果你想知道应用运行的HTTP接口,通过关键字local.server.port可以得到这个属性。

 

Take care when enabling this feature as the MBean exposes a method to shutdown the application.

 

当启用这个功能时要非常小心,因为MBean会暴露一个关闭应用的方法。

推荐阅读更多精彩内容