您的位置:首页 > 编程语言 > Java开发

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

2016-11-17 19:01 423 查看
文章作者: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.AutoConfigurationReportLoggingInitializer
DEBUG
日志。

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.gif
banner.jpg
banner.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

VariableDescription
${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变量

VariableDescription
${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
允许你链接多个方法调用,包括允许你创建分层的
parent
child
方法。

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框架事件之外,例如
ContextRefreshedEvent
SpringApplication
会发送一些其它的应用事件。

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:

An
ApplicationStartedEvent
, but before any processing except 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
ApplicationPreparedEvent
is sent just before the refresh is started, but after bean definitions have been loaded.

An
ApplicationReadyEvent
is sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests.

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

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

在运行启动时发送
ApplicationStartedEvent
,除了监听器和初始化器注册之外,在进行任何处理之前发送。

当在上下文中使用的
Environment
已知时,发送
ApplicationEnvironmentPreparedEvent
,但发送是在上下文创建之前。

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


在再刷新之后,发送
ApplicationReadyEvent
,任何相关的回调函数都处理完成之后,意味着应用已经准备处理服务请求了。

如果启动时出现异常,发送
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
类型。默认情况下,会使用
AnnotationConfigApplicationContext
AnnotationConfigEmbeddedWebApplicationContext
,依赖于你是否在开发一个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[]
和转换的
option
non-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
启动时运行一些特定的代码,你可以实现
ApplicationRunner
CommandLineRunner
接口。这两个接口以同样方式工作,并有一个单独的
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.

另外,如果定义的
CommandLineRunner
ApplicationRunner
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会暴露一个关闭应用的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: