SpringBoot官方文档翻译(三十六):访问应用程序参数

23.6 Accessing Application Arguments(访问应用程序参数)

1
2
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,     
as shown in the following example:

您可以通过注入一个org.springframework.boot.ApplicationArguments bean去获取访问通过SpringApplication.run(… )传递的参数。ApplicationArguments参数接口即提供了访问原生String[]参数的方式,也提供了访问解析option(可选)和non-option(非可选)参数。举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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"]
}

}

1
2
3
Spring Boot also registers a CommandLinePropertySource with the    
Spring Environment. This lets you also inject single application
arguments by using the @Value annotation.

Spring Boot还向Spring环境注册了一个CommandLinePropertySource。这使您同样能够通过使用注解@Value注入单应用参数。

分享到

SpringBoot官方文档翻译(三十六):访问应用程序参数

23.6 Accessing Application Arguments(访问应用程序参数)

1
2
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,     
as shown in the following example:

您可以通过注入一个org.springframework.boot.ApplicationArguments bean去获取访问通过SpringApplication.run(… )传递的参数。ApplicationArguments参数接口即提供了访问原生String[]参数的方式,也提供了访问解析option(可选)和non-option(非可选)参数。举个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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"]
}

}

1
2
3
Spring Boot also registers a CommandLinePropertySource with the    
Spring Environment. This lets you also inject single application
arguments by using the @Value annotation.

Spring Boot还向Spring环境注册了一个CommandLinePropertySource。这使您同样能够通过使用注解@Value注入单应用参数。

请为以下账号开通访问 http://qahome.dp/smsqueue/query 的权限
wbhz_zhengzhongguo
wbhz_178304746
wbhz_majing_fzlzh
wbhz_songchang
wbhz_ganjiali
wbhz_lushen
wbhz_fangjie

分享到

SpringBoot官方文档翻译(三十五):web环境

23.6 Web Environment(web环境)

1
2
3
A SpringApplication attempts to create the right type of     
ApplicationContext on your behalf. The algorithm used to
determine a WebEnvironmentType is fairly simple:

SpringApplication试图根据您的行为创建正确的ApplicationContext类型,用于确定WebEnvironmentType的算法非常简单:

1
2
3
•	If Spring MVC is present, an AnnotationConfigServletWebServerApplicationContext is used
• If Spring MVC is not present and Spring WebFlux is present, an AnnotationConfigReactiveWebApplicationContext is used
• Otherwise, AnnotationConfigApplicationContext is used

  • 如果使用的是Spring MVC的框架,AnnotationConfigServletWebServerApplicationContext将会被使用
  • 如果使用的不是Spring MVC框架,使用的是WebFlux框架,AnnotationConfigReactiveWebApplicationContext上下文将会被使用
  • 其他情况,AnnotationConfigApplicationContext将会被使用
    1
    2
    3
    4
    This means that if you are using Spring MVC and the new WebClient     
    from Spring WebFlux in the same application, Spring MVC will be used
    by default. You can override that easily by
    calling setWebApplicationType(WebApplicationType).

这意味着,如果您在同一个应用中使用了Spring MVC也使用了Spring WebFlux的Web客户端,Spring MVC将会作为默认框架。您可以通过setWebApplicationType(WebApplicationType).来重写这个默认。

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

也可以通过调用setApplicationContextClass(… )来设置上下文的类型。

1
2
It is often desirable to call setWebApplicationType(WebApplicationType.NONE)     
when using SpringApplication within a JUnit test.

当使用JUnit测试的时候也可以使用setWebApplicationType(WebApplicationType.NONE)来设置上下文类型。

分享到

SpringBoot官方文档翻译(三十四):应用事件和监听

23.5 Application Events and Listeners(应用事件和监听)

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

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

1
2
3
4
5
6
7
8
9
10
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

一些事件其实是在应用上下文创建之前就已经创建了,所以您不能够通过@Bean给这些事件增加监听。您可以通过SpringApplication.addListeners(… )方法或者SpringApplicationBuilder.listeners(… )方法来给这些事件注册监听。
如果您想这些事件自动注册,而不管应用是否被创建,您可以通过增加META-INF/spring.factories文件到您的项目中,然后通过org.springframework.context.ApplicationListener作为key关联您的监听,如下例子:org.springframework.context.ApplicationListener=com.example.project.MyListener

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

随着您的应用程序运行,应用程序事件按以下顺序发送:

1
2
3
4
5
6
1.	An ApplicationStartingEvent is sent at the start of a run but before any processing, except for 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 ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called.
5. An ApplicationReadyEvent is sent after any application and command-line runners have been called. It indicates that the application is ready to service requests.
6. An ApplicationFailedEvent is sent if there is an exception on startup.

  • 1.ApplicationStartingEvent 会在程序注册完监听器和初始器之后,其他所有进程运行之前发送。
  • 2.ApplicationEnvironmentPreparedEvent 在Environment被使用之后,容器被创建之前发送。
  • 3.ApplicationPreparedEvent在刷新启动之前,但在加载了bean定义之后发送。
  • 4.ApplicationStartedEvent在上下文被刷新之后,任何应用和command-line运行之前将被调用
  • 5.ApplicationReadyEvent在刷新启动之后被发送,并且处理了任何相关的回调以指示应用程序准备好服务请求。
  • 6.ApplicationFailedEvent如果启动时发生异常发送。
1
2
3
You often need not 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使用事件来处理各种任务。

1
2
3
4
5
6
7
Application events are sent by using Spring Framework’s event     
publishing mechanism. Part of this mechanism ensures that an
event published to the listeners in a child context is also
published to the listeners in any ancestor contexts. As a result
of this, if your application uses a hierarchy of SpringApplication 
instances, a listener may receive multiple instances of the same
type of application event.

应用事件发送是采用的Spring框架的事件发布机制。该机制的一部分确保发布给子上下文中侦听器的事件也会发布给任何祖先上下文中的侦听器。因此,如果您的应用使用的是SpringApplication级联结构实例化,监听器可以接收同一类型的应用程序事件的多个实例。

1
2
3
4
5
6
To allow your listener to distinguish between an event for its context     
and an event for a descendant context, it should request that its
application context is injected and then compare the injected context
with the context of the event. The context can be injected by
implementing ApplicationContextAware or, if the listener is a bean,
by using @Autowired.

允许您的侦听器区分其上下文的事件和后代上下文的事件,它应该请求注入它应用的上下文,并比较注入上线文的事件。上线文可以通过实现ApplicationContextAware接口注入,或者如果监听是个bean可以通过@Autowired来注入

分享到

SpringBoot官方文档翻译(三十三):流式编程接口

23.4 Fluent Builder API(流式编程接口)

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

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

1
2
3
The SpringApplicationBuilder lets you chain together multiple method     
calls and includes parent and child methods that let you create a
hierarchy, as shown in the following example:

SpringApplicationBuilder可以让您将多个方法之间的调用使用父子关系的方式链接起来,如下:

1
2
3
4
5
new SpringApplicationBuilder()
.sources(Parent.class)
.child(Application.class)
.bannerMode(Banner.Mode.OFF)
.run(args);

1
2
3
4
5
There are some restrictions when creating an ApplicationContext     
hierarchy. For example, Web components must be contained within
the child context, and the same Environment is used for both parent
and child contexts. See the SpringApplicationBuilder Javadoc for
full details.

像这种链式编程有一些限制。例如,Web组件必须包含在子上下文中,一些环境变量即会被用在父上下文中也会用在子上下文中。具体可以参考SpringApplicationBuilder的Javadoc。

分享到

SpringBoot官方文档翻译(三十二):定制SpringApplication

23.3 Customizing SpringApplication(定制SpringApplication)

1
2
3
If the SpringApplication defaults are not to your taste, you can instead     
create a local instance and customize it. For example, to turn off the
banner, you could write:

如果SpringApplication默认设置不符合您的口味,您可以创建一个本地实例替换定制它。举个例子,想要关闭banner您可以这样写:

1
2
3
4
5
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
1
2
3
4
5
The constructor arguments passed to SpringApplication are     
configuration sources for Spring beans. In most cases, these
are references to @Configuration classes, but they could also
be references to XML configuration or to packages that should
be scanned.

传递给SpringApplication的构造函数参数是Spring bean的配置源。在大多数情况下,这将会关联到一个@Configuration的配置类,但它同样支持关联到XML配置或者关联到那些需要被扫描的包。

1
2
3
It is also possible to configure the SpringApplication by     
using an application.properties file. See Chapter 24, Externalized Configuration for details.
For a complete list of the configuration options, see the SpringApplication Javadoc.

同样可以使用application.properties来配置SpringApplication。细节请查看章节24“Externalized Configuration ”。
需要了解完整的可选配置,请查看SpringApplication的Javadoc或者源码。

分享到

SpringBoot官方文档翻译(三十一):定制Banner

23.2 Customizing the Banner(定制Banner)

1
2
3
4
5
6
7
8
9
The banner that is printed on start up can be changed by adding a     
banner.txt file to your classpath or by setting
the spring.banner.location property to the location of such a file.
If the file has an encoding other than UTF-8, you can set 
spring.banner.charset. 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 the spring.banner.image.location property. Images
are converted into an ASCII art representation and printed above
any text banner.

当应用启动的时候显示的那个Banner是可以被放在类路径下的banner.txt所改变,或者通过设置spring.banner.location属性来指定bannner的位置。如果该banner文件的编码格式不是UTF-8,您可以通过设置spring.banner.charset来指定编码格式。除了text文件以外,您还可以指定一个banner.gif格式的文件,或者banner.jpg或者banner.png的图片文件到您类路径下,或者通过设置spring.banner.image.location属性来指定该图片位置。图片被转换成ASCII艺术表示并在上面打印任何文字横幅。

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

在banner.txt文件中,您可以使用以下任何占位符:

属性 描述
${application.version} 您应用的版本信息,诸如定义在MANIFEST.MF中的。举个例子,Implementation-Version: 1.0 则打印1.0.
${application.formatted-version} 同上,并且被格式化后显示 (用括号包围,并以v开头). 举个例子(v1.0).
${spring-boot.version} Spring Boot的版本。举个例子(v2.1.0.BUILD-SNAPSHOT).
${spring-boot.formatted-version} 同上,并且被格式化后显示(用括号包围,并以v开头). 举个例子 (v2.1.0.BUILD-SNAPSHOT).
${Ansi.NAME} (or ${AnsiColor.NAME},${AnsiBackground.NAME}, ${AnsiStyle.NAME}) 其中NAME是ANSI转义代码的名称,可以参考https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/ansi/AnsiPropertySource.java
${application.title} 您的应用的标题,定义在MANIFEST.MF中。举个例子Implementation-Title: MyApp则打印“MyApp”
1
2
3
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()方法。

1
2
3
You can also use the spring.main.banner-mode property to determine if     
the banner has to be printed on System.out (console), sent to the
configured logger (log), or not produced at all (off).

您也可以使用spring.main.banner-mode属性来确定是否横幅必须打印在System.out(控制台)上,发送到配置记录器(日志),或根本不生产(关闭)。

1
2
The printed banner is registered as a singleton bean under     
the following name: springBootBanner.

打印banner被注册为一个名为“springBootBanner”的单例bean。

1
2
3
4
5
YAML maps off to false, so be sure to add quotes if you want to     
disable the banner in your application, as shown in the following example:
spring:
main:
banner-mode: "off"

YAML映射“off”为“false”,因此如果您想在应用程序中禁用横幅,请务必添加引号。

分享到

SpringBoot官方文档翻译(三十):启动失败

23.1 Startup Failure(启动失败)

1
2
3
4
5
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 message:

如果您的应用启动失败了,注册的FailureAnalyzers将获得有机会提供专门的错误信息和具体行动
解决问题。举个例子,如果您子啊端口8080启动一个应用,而此端口已经被使用了,将会出现如下信息:

1
2
3
4
5
6
7
8
9
10
11
***************************
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.

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

Spring Boot提供了众多的FailureAnalyzer实现,您可以加入您自身的实现。

1
2
3
4
If no failure analyzers are able to handle the exception, you can     
still display the full conditions 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.ConditionEvaluationReportLoggingListener.

如果没有错误分析器能够处理这个异常,依然可以展示整个的条件报告去了解到底什么出错了。这样做,您需要为以下包或者类开启debug属性或者开启DEBUG日志:org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

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

举个例子,如果您使用java -jar去运行您的应用,您能够通过开启debug属性,如下:

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

分享到

SpringBoot官方文档翻译(二十九):Spring Boot的功能

Part IV. Spring Boot features(Spring Boot的功能)

1
2
3
4
5
This section dives into the details of Spring Boot. Here you can learn     
about the key features that you may want to use and customize. If you
have not already done so, 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.

本章节将介绍SPirng Boot的细节,您可以学习到你想使用和定制的关键功能。如果您还没有准备好,您可以阅读第二部分“Getting Started”和第三部分“Using Spring Boot”章节,这样您可以具备良好的基础知识。

23. SpringApplication

1
2
3
4
The SpringApplication class provides a convenient way to bootstrap     
a Spring application that is started from a main() method. In many
situations, you can delegate to the static SpringApplication.run 
method, as shown in the following example:

SpringApplication类提供了一个非常便捷的方式通过main()方法去启动Spring应用。在大多数情况下,您可以通过委托给静态方法SpringApplication.run()去启动,如下:

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

1
2
When your application starts, you should see something similar     
to the following output:

当您的应用启动后,您将看到如下的景象:

1
2
3
4
5
6
7
8
9
10
11
12
  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: v2.1.0.BUILD-SNAPSHOT

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] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@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.TomcatServletWebServerFactory : 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)

1
2
3
4
By default, INFO logging messages are shown, including some     
relevant startup details, such as the user that launched the
application. If you need a log level other than INFO, you can
set it, as described in Section 26.4, “Log Levels”,

默认情况下,INFO级别的日志将会展示出来,包括一些相应的启动细节,诸如启动程序的用户等。如果您需要展示不仅仅是INFO级别的日志,您可以设置它,详情参照26.4章节“Log Levels”。

分享到

SpringBoot官方文档翻译(二十八):生产环境打包

21. Packaging Your Application for Production(生产环境打包)

1
2
Executable jars can be used for production deployment. As they     
are self-contained, they are also ideally suited for cloud-based deployment.

可运行的jars包能够被用于生成环境部署。由于它们是独立的,它们也非常适合基于云的部署。

1
2
3
For additional “production ready” features, such as health, auditing,     
and metric REST or JMX end-points, consider adding spring-boot-actuator.
See Part V, “Spring Boot Actuator: Production-ready features” for details.

对于其他的“生产就绪”的功能,诸如健康检测,审计,REST风格埋点或者JMX的断点,考虑引入spring-boot-actuator。参照第五部分,“Spring Boot Actuator: Production-ready features”获取更多的细节。

22. What to Read Next(接下去读什么)

1
2
3
4
You should now understand how you can use Spring Boot and some best     
practices that you should follow. You can now go on to learn about
specific Spring Boot featuresin depth, or you could skip ahead and
read about the “production ready” aspects of Spring Boot.

目前您已经知道如何使用Spring Boot和一些您需要遵守的最佳实践。您可以继续学习Spring Boo的一些特殊的特性。或者您也可以越过这些去切入阅读Spring Boot的“生产准备”。

分享到