文章作者: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
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 theorg.springframework.boot.Banner
interface and implement your ownprintBanner()
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
tofalse
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 sameEnvironment
will be used for both parent and child contexts. See theSpringApplicationBuilder
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 theSpringApplication.addListeners(…)
orSpringApplicationBuilder.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 theorg.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 theEnvironment
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 usingSpringApplication
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 SpringEnvironment
. 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会暴露一个关闭应用的方法。