Spring Boot 2.0.0参考手册_中英文对照_Part IV_23
2016-11-17 19:01
423 查看
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
这一部分进入Spring Boot细节部分。在这部分你会了解到你想使用和定制的一些重要特性。如果你还没准备好,你可以阅读第二部分“Getting started”和第三部分“Using Spring Boot”,可以对基础知识有个较好的认识。
When your application starts you should see something similar to the following:
当你的应用启动时你应该看到类似于下面的东西:
By default
默认情况下会输出
如果你的应用启动失败,注册
Spring Boot provides numerous
Spring Boot提供了许多
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
如果没有失败分析器能处理这个异常,你仍可以显示完整的自动配置报告,从而更好的理解什么地方出问题了。为了实现这个你需要启用
For instance, if you are running your application using
例如,如果你使用
启动时打印的标语可以通过在classpath中添加一个
Inside your
在
Table 23.1. Banner variables
Table 23.1. Banner变量
The
如果你想自动生成一个标语你可以使用
You can also use the
你也可以使用
The printed banner will be registered as a singleton bean under the name
输出的banner会注册名字为
YAML maps
如果你想在你的应用中禁用banner,YAML会将
如果你不喜欢默认的
The constructor arguments passed to
传给
It is also possible to configure the
也可以使用
For a complete list of the configuration options, see the
完整的配置选项列表,请看
如果你需要构建
The
For example:
例如:
There are some restrictions when creating an
当创建
除了平常的Spring框架事件之外,例如
Some events are actually triggered before the
If you want those listeners to be registered automatically regardless of the way the application is created you can add a
在
如果你想自动注册这些监听器,不管上下文的创建方式,你可以在你的工程中添加
Application events are sent in the following order, as your application runs:
An
An
An
An
An
当你的应用运行时,应用事件以下面的顺序发送:
在运行启动时发送
当在上下文中使用的
在再刷新启动之前,但在bean定义加载之后,发送
在再刷新之后,发送
如果启动时出现异常,发送
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内部使用事件来处理大量的任务。
The algorithm used to determine a ‘web environment’ is fairly simplistic (based on the presence of a few classes). You can use
使用的决定
It is also possible to take complete control of the
完全控制
It is often desirable to call
当在JUnit测试时使用
如果你需要访问传进
Spring Boot will also register a
Spring Boot也在Spring
如果你需要在
The
You can additionally implement the
另外,如果定义的
为了确保
In addition, beans may implement the
另外,当应用退出时,如果想返回一个指定的退出码,beans可以实现
如果应用想启用admin相关的功能,可以指定
If you want to know on which HTTP port the application is running, get the property with key
如果你想知道应用运行的HTTP接口,通过关键字
Take care when enabling this feature as the MBean exposes a method to shutdown the application.
当启用这个功能时要非常小心,因为MBean会暴露一个关闭应用的方法。
博客: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
TheSpringApplicationclass 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.runmethod:
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
INFOlogging 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, registeredFailureAnalyzersget 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
8080and 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
FailureAnalyzerimplementations 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
debugproperty or enable
DEBUGlogging 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 -jaryou can enable the
debugproperty 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 abanner.txtfile to your classpath, or by setting
banner.locationto 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.jpgor
banner.pngimage file to your classpath, or set a
banner.image.locationproperty. 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.txtfile 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.0is printed as 1.0. |
${application.formatted-version} | The version number of your application as declared in MANIFEST.MFformatted 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 NAMEis the name of an ANSI escape code. See AnsiPropertySourcefor details. |
${application.title} | The title of your application as declared in MANIFEST.MF. For example Implementation-Title: MyAppis printed as MyApp. |
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. |
SpringApplication.setBanner(…)method can be used if you want to generate a banner programmatically. Use the
org.springframework.boot.Bannerinterface and implement your own
printBanner()method.
如果你想自动生成一个标语你可以使用
SpringApplication.setBanner(…)方法。使用
org.springframework.boot.Banner接口并实现你自己的
printBanner()方法。
You can also use the
spring.main.banner-modeproperty 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
offto
falseso 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 theSpringApplicationdefaults 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
SpringApplicationare configuration sources for spring beans. In most cases these will be references to
@Configurationclasses, 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
SpringApplicationusing an
application.propertiesfile. See Chapter 24, Externalized Configuration for details.
也可以使用
application.properties文件配置
SpringApplication。更多细节请看24章,『外部配置』。
For a complete list of the configuration options, see the
SpringApplicationJavadoc.
完整的配置选项列表,请看
SpringApplication文档。
23.4 Fluent builder API
If you need to build anApplicationContexthierarchy (multiple contexts with a parent/child relationship), or if you just prefer using a
fluentbuilder API, you can use the
SpringApplicationBuilder.
如果你需要构建
ApplicationContext分层(多个具有父/子关系的上下文),或者你更喜欢使用
fluent的构建器API,你可以使用
SpringApplicationBuilder。
The
SpringApplicationBuilderallows you to chain together multiple method calls, and includes
parentand
childmethods 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
ApplicationContexthierarchy, e.g. Web components must be contained within the child context, and the same
Environmentwill be used for both parent and child contexts. See the
SpringApplicationBuilderJavadoc for full details.
当创建
ApplicationContext分层时有一些限制,例如,子上下文必须包含web组件,父子上下文将使用同一个
Environment。更完整的细节请看
SpringApplicationBuilder文档。
23.5 Application events and listeners
In addition to the usual Spring Framework events, such asContextRefreshedEvent, a
SpringApplicationsends some additional application events.
除了平常的Spring框架事件之外,例如
ContextRefreshedEvent,
SpringApplication会发送一些其它的应用事件。
Some events are actually triggered before the
ApplicationContextis 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.factoriesfile to your project and reference your listener(s) using the
org.springframework.context.ApplicationListenerkey.
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
ApplicationEnvironmentPreparedEventis sent when the
Environmentto be used in the context is known, but before the context is created.
An
ApplicationPreparedEventis sent just before the refresh is started, but after bean definitions have been loaded.
An
ApplicationReadyEventis sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests.
An
ApplicationFailedEventis 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
ASpringApplicationwill attempt to create the right type of
ApplicationContexton your behalf. By default, an
AnnotationConfigApplicationContextor
AnnotationConfigEmbeddedWebApplicationContextwill 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
ApplicationContexttype that will be used by calling
setApplicationContextClass(…).
完全控制
ApplicationContext类型也是可能的,通过调用
setApplicationContextClass(…)使用。
It is often desirable to call
setWebEnvironment(false)when using
SpringApplicationwithin a JUnit test.
当在JUnit测试时使用
SpringApplication,经常需要调用
setWebEnvironment(false)。
23.7 Accessing application arguments
If you need to access the application arguments that were passed toSpringApplication.run(…)you can inject a
org.springframework.boot.ApplicationArgumentsbean. The
ApplicationArgumentsinterface provides access to both the raw
String[]arguments as well as parsed
optionand
non-optionarguments:
如果你需要访问传进
SpringApplication.run(…)中的应用参数,你可以注入
org.springframework.boot.ApplicationArgumentsbean。
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
CommandLinePropertySourcewith the Spring
Environment. This allows you to also inject single application arguments using the
@Valueannotation.
Spring Boot也在Spring
Environment中注册
CommandLinePropertySource。这也允许你使用
@Value注解注入单个应对参数。
23.8 Using the ApplicationRunner or CommandLineRunner
If you need to run some specific code once theSpringApplicationhas started, you can implement the
ApplicationRunneror
CommandLineRunnerinterfaces. Both interfaces work in the same way and offer a single
runmethod which will be called just before
SpringApplication.run(…)completes.
如果你需要在
SpringApplication启动时运行一些特定的代码,你可以实现
ApplicationRunner或
CommandLineRunner接口。这两个接口以同样方式工作,并有一个单独的
run方法,在
SpringApplication.run(…)之前会调用这个
run方法。
The
CommandLineRunnerinterfaces provides access to application arguments as a simple string array, whereas the
ApplicationRunneruses the
ApplicationArgumentsinterface 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.Orderedinterface or use the
org.springframework.core.annotation.Orderannotation if several
CommandLineRunneror
ApplicationRunnerbeans are defined that must be called in a specific order.
另外,如果定义的
CommandLineRunner或
ApplicationRunnerbeans必须以指定顺序调用,你可以实现
org.springframework.core.Ordered接口或
org.springframework.core.annotation.Order注解。
23.9 Application exit
EachSpringApplicationwill register a shutdown hook with the JVM to ensure that the
ApplicationContextis closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the
DisposableBeaninterface, or the
@PreDestroyannotation) can be used.
为了确保
ApplicationContext在关闭时安全退出, 每个
SpringApplication都会在JVM中注册一个关闭钩子。所有的标准Spring生命周期回调函数(例如
DisposableBean接口,或
@PreDestroy注解)都会被使用。
In addition, beans may implement the
org.springframework.boot.ExitCodeGeneratorinterface 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 thespring.application.admin.enabledproperty. This exposes the
SpringApplicationAdminMXBeanon 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会暴露一个关闭应用的方法。
相关文章推荐
- Spring Boot 2.0.0参考手册_中英文对照_Part IV_26
- Spring Boot 2.0.0参考手册_中英文对照_Part IV_24
- Spring Boot 2.0.0参考手册_中英文对照_Part IV_25
- Spring Boot 2.0.0参考手册_中英文对照_Part III_13
- Spring Boot 2.0.0参考手册_中英文对照_Part III_14-18
- Spring Boot 2.0.0参考手册_中英文对照_Part II_8-10
- Spring Boot 2.0.0参考手册_中英文对照_Part II_11-12
- Spring Boot 2.0.0参考手册_中文版_Part IV_23
- Spring Boot 2.0.0参考手册_中文版_Part IV_25
- Spring Boot 2.0.0参考手册_中文版_Part IV_26
- Spring Boot 2.0.0参考手册_中文版_Part I
- Spring Boot 2.0.0参考手册_中文版_Part II_11-12
- Spring Boot 2.0.0参考手册_中英文对照_Part III_19-22
- Spring Boot 2.0.0参考手册_中文版_Part II_8-10
- Spring Boot 2.0.0参考手册_中英文对照_Part I
- Spring Boot 2.0.0参考手册_中文版_Part III_19-22
- Spring框架参考手册_5.0.0_中英文对照版_Part II_3.2
- Spring框架参考手册_5.0.0_中英文对照版_Part II_3.6
- Spring框架参考手册_5.0.0_中英文对照版_Part I_第二章
- Spring框架参考手册_5.0.0_中英文对照版_Part II_3.9