- Term
- Chapter 4. Getting Started
- Chapter 5. Upgrading Spring Boot
- Chapter 6. Developing with Spring Boot
- Chapter 7. Spring Boot Features
- 7.1 SpringApplication
- 7.1.1 Startup Failure
- 7.1.2 Lazy Initialization
- 7.1.3 Customizing the Banner
- 7.1.4 Customizing SpringApplication
- 7.1.6 Application Availability
- 7.1.7 Application Events and Listeners
- 7.1.8 Web Environment
- 7.1.9 Accessing Application Arguments
- 7.1.10 Using the ApplicationRunner or CommandLineRunner
- 7.1.11 Application Exit
- 7.1.12 Admin Features
- 7.1.13 Application Startup Tracking
- 7.2 Externalized Configuration
- 7.3 Profiles
- 7.4 Logging
- 7.5 Internationalization
- 7.6 JSON
- 7.7 Developing Web Applications
- 7.1 SpringApplication
Mongoosej.Blog.Software.Programming.Java.Framework.Spring.SpringBoot.Spring Boot Reference Document
Term
Spring Boot CLI (Command Line Interface)
Chapter 4. Getting Started
4.1Introducing Spring Boot
Spring Boot helps you to create stand-alone, production-grade Spring-based applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
SpringBoot帮助您创建可以运行的独立的、生产级的基于Spring的应用程序。我们对Spring平台和第三方库持有一种固执己见的观点,这样您就可以用最少的麻烦开始了。大多数Spring引导应用程序只需要很少的Spring配置。
4.2 System Requirements
Spring Boot 2.5.4 requires Java 8 and is compatible up to and including Java 16. Spring Framework
5.3.9 or above is also required.
Chapter 5. Upgrading Spring Boot
5.2 Upgrading to a new feature release
Spring Boot provides a way to analyze your application’s environment and print diagnostics at startup, but also temporarily migrate properties at runtime for you.
SpringBoot提供了一种在启动时分析应用程序环境和打印诊断的方法,但也可以在运行时为您临时迁移属性。
Chapter 6. Developing with Spring Boot
6.1 Build System
Each release of Spring Boot provides a curated list of dependencies that it supports. In practice, you do not need to provide a version for any of these dependencies in your build configuration, as Spring Boot manages that for you. When you upgrade Spring Boot itself, these dependencies are upgraded as well in a consistent way.
SpringBoot的每个版本都提供了它所支持的依赖项的详细列表。实际上,您不需要在构建配置中为这些依赖项中的任何一个提供版本,因为SpringBoot会为您管理这些依赖项。升级Spring Boot本身时,这些依赖项也会以一致的方式升级。
You can still specify a version and override Spring Boot’s recommendations if you need to do so.
Each release of Spring Boot is associated with a base version of the Spring Framework. We highly recommend that you not specify its version.
The following application starters are provided by Spring Boot under the org.springframework.boot group:
Table 1. Spring Boot application starters
6.2 Structuring Your Code
When a class does not include a package declaration, it is considered to be in the “default package”. The use of the “default package” is generally discouraged and should be avoided. It can cause particular problems for Spring Boot applications that use the @ComponentScan,@ConfigurationPropertiesScan, @EntityScan, or @SpringBootApplication annotations, since every class from every jar is read.
当一个类不包含包声明时,它被认为是在“默认包”中。通常不鼓励使用“默认包”,应避免使用。对于使用@ComponentScan、@ConfigurationPropertiesScan、@EntityScan或@SpringBootApplication注释的Spring引导应用程序,它可能会导致特定的问题,因为每个jar中的每个类都是读取的。
We generally recommend that you locate your main application class in a root package above other classes. The @SpringBootApplication annotation is often placed on your main class, and it implicitly defines a base “search package” for certain items. For example, if you are writing a JPA application, the package of the @SpringBootApplication annotated class is used to search for @Entity items. Using a root package also allows component scan to apply only on your project.
我们通常建议您将主应用程序类定位在根包中,高于其他类。@SpringBootApplication注释通常放在主类上,它隐式地为某些项目定义了一个基本的“搜索包”。例如,如果您正在编写JPA应用程序,@SpringBootApplication注释类的包用于搜索@Entity项。使用根包还允许组件扫描仅应用于您的项目。
6.5 Spring Beans and Dependency Injection
If you structure your code as suggested above (locating your application class in a top package), you can add @ComponentScan without any arguments or use the @SpringBootApplication annotation which implicitly includes it. All of your application components (@Component, @Service, @Repository, @Controller etc.) are automatically registered as Spring Beans.
6.6 Using the @SpringBootApplication Annotation
Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their “application class”. A single @SpringBootApplication annotation can be used to enable those three features.
Chapter 7. Spring Boot Features
7.1 SpringApplication
讲述了SpringApplication类的一些特性及设置方式。其实也就是SpringBoot的自动配置特性,在需要手动配置时,你可以配置哪些特性,以及如何配置。
7.1.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.
Spring Boot provides numerous FailureAnalyzer implementations, and you can add your own.
7.1.2 Lazy Initialization
For these reasons, lazy initialization is not enabled by default.
Lazy initialization can be enabled programmatically using the lazyInitialization method on SpringApplicationBuilder or the setLazyInitialization method on SpringApplication. Alternatively, it can be enabled using the spring.main.lazy-initialization property.
7.1.3 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 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.txt文件或将spring.banner.location属性设置为此类文件的位置来更改启动时打印的横幅。如果文件的编码不是UTF-8,则可以设置spring.banner.charset。除了文本文件外,还可以将banner.gif、banner.jpg或banner.png图像文件添加到类路径中,或设置spring.banner.image.location属性。图像转换为ASCII艺术表现形式,并打印在任何文本横幅上方。
启动横幅:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.4)
7.1.4 Customizing SpringApplication
If the SpringApplication defaults are not to your taste, you can instead create a local instance and customize it.
It is also possible to configure the SpringApplication by using an application.properties file. See Externalized Configuration for details (7.2).
7.1.6 Application Availability
When deployed on platforms, applications can provide information about their availability to the platform using infrastructure such as Kubernetes Probes. Spring Boot includes out-of-the box support for the commonly used “liveness” and “readiness” availability states. If you are using Spring Boot’s “actuator” support then these states are exposed as health endpoint groups.
在平台上部署时,应用程序可以使用Kubernetes探测器等基础设施向平台提供有关其可用性的信息。Spring Boot包括对常用的“活跃性”和“就绪性”可用性状态的开箱即用支持。如果您使用SpringBoot的“执行器”支持,那么这些状态将作为健康端点组公开。
7.1.7 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还发送一些附加的应用程序事件。
Application events are sent in the following order, as your application runs:
- An ApplicationStartingEvent is sent at the start of a run but before any processing, except for
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 ApplicationContextInitializedEvent is sent when the ApplicationContext is prepared and
ApplicationContextInitializers have been called but before any bean definitions are loaded. - An ApplicationPreparedEvent is sent just before the refresh is started but after bean definitions
have been loaded. - An ApplicationStartedEvent is sent after the context has been refreshed but before any
application and command-line runners have been called. - An AvailabilityChangeEvent is sent right after with LivenessState.CORRECT to indicate that the
application is considered as live. - An ApplicationReadyEvent is sent after any application and command-line runners have been
called. - An AvailabilityChangeEvent is sent right after with ReadinessState.ACCEPTING_TRAFFIC to indicate
that the application is ready to service requests. - An ApplicationFailedEvent is sent if there is an exception on startup.
The above list only includes SpringApplicationEvents that are tied to a SpringApplication. In addition to these, the following events are also published after ApplicationPreparedEvent and before ApplicationStartedEvent:
- A WebServerInitializedEvent is sent after the WebServer is ready. ServletWebServerInitializedEvent and ReactiveWebServerInitializedEvent are the servlet and reactive variants respectively.
- A ContextRefreshedEvent is sent when an ApplicationContext is refreshed.
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使用事件来处理各种任务。
Event listeners should not run potentially lengthy tasks as they execute in the same thread by default. Consider using application and command-line runners instead.
默认情况下,事件侦听器不应在同一线程中执行可能很长的任务。请考虑使用应用程序和命令行运行器。
7.1.8 Web Environment
A SpringApplication attempts to create the right type of ApplicationContext on your behalf. The algorithm used to determine a WebApplicationType is the following…
It is often desirable to call setWebApplicationType(WebApplicationType.NONE) when the application should not run as a web application and should not start an embedded web server.
7.1.9 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 nonoption arguments.
如果需要访问传递给SpringApplication.run(…)的应用程序参数,可以注入org.springframework.boot.ApplicationArguments bean。ApplicationArguments接口提供对原始字符串[]参数以及解析的选项和非选项参数的访问。
7.1.10 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 is called just before SpringApplication.run(…) completes.
This contract is well suited for tasks that should run after application startup but before it starts accepting traffic.
If several CommandLineRunner or ApplicationRunner beans are defined that must be called in a specific order, you can additionally implement the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation.
7.1.11 Application Exit
Each SpringApplication registers a shutdown hook with the JVM to ensure that the ApplicationContext closes gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface or the @PreDestroy annotation) can be used.
7.1.12 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 feature could also be useful for any service wrapper implementation.
7.1.13 Application Startup Tracking
During the application startup, the SpringApplication and the ApplicationContext perform many tasks related to the application lifecycle, the beans lifecycle or even processing application events. With ApplicationStartup, Spring Framework allows you to track the application startup sequence with StartupStep objects. This data can be collected for profiling purposes, or just to have a better understanding of an application startup process.
Spring Boot can also be configured to expose a startup endpoint that provides this information as a JSON document.
7.2 Externalized Configuration
Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, include Java properties files, YAML files, environment variables, and command-line arguments.
Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Properties are considered in the following order (with values from lower items overriding earlier ones):
Config data files are considered in the following order:
It is recommended to stick with one format for your entire application. If you have configuration files with both .properties and .yml format in the same location, .properties takes precedence.
7.2.1 Accessing Command Line Properties
By default, SpringApplication converts any command line option arguments (that is, arguments starting with —, such as —server.port=9000) to a property and adds them to the Spring Environment. As mentioned previously, command line properties always take precedence over file based property sources.
If you do not want command line properties to be added to the Environment, you can disable them by using SpringApplication.setAddCommandLineProperties(false).
7.2.2 JSON Application Properties
Environment variables and system properties often have restrictions that mean some property names cannot be used. To help with this, Spring Boot allows you to encode a block of properties into a single JSON structure.
When your application starts, any spring.application.json or SPRING_APPLICATION_JSON properties will be parsed and added to the Environment.
7.2.3 External Application Properties
Spring Boot will automatically find and load application.properties and application.yaml files from the following locations when your application starts:
- From the classpath
a. The classpath root
b. The classpath /config package - From the current directory
a. The current directory
b. The /config subdirectory in the current directory
c. Immediate child directories of the /config subdirectory
If you do not like application as the configuration file name, you can switch to another file name by specifying a spring.config.name environment property.
You can also refer to an explicit location by using the spring.config.location environment property.
7.2.4 Encrypting Properties
Spring Boot does not provide any built in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring Environment.
7.2.5 Working with YAML
YAML is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. The SpringApplication class automatically supports YAML as an alternative to properties whenever you have the SnakeYAML library on your classpath.
YAML files cannot be loaded by using the @PropertySource or @TestPropertySource annotations. So, in the case that you need to load values that way, you need to use a properties file.
Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean loads YAML as Properties and the YamlMapFactoryBean loads YAML as a Map.
You can also use the YamlPropertySourceLoader class if you want to load YAML as a Spring PropertySource.
7.2.6 Configuring Random Values
The RandomValuePropertySource is useful for injecting random values (for example, into secrets or test cases). It can produce integers, longs, uuids, or strings.
7.2.7 Configuring System Environment Properties
Spring Boot supports setting a prefix for environment properties. This is useful if the system environment is shared by multiple Spring Boot applications with different configuration requirements. The prefix for system environment properties can be set directly on SpringApplication.
For example, if you set the prefix to input, a property such as remote.timeout will also be resolved as input.remote.timeout in the system environment.
7.2.8 Type-safe Configuration Properties
Using the @Value(“${property}”) annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that lets strongly typed beans govern and validate the configuration of your application.
7.3 Profiles
Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments. Any @Component, @Configuration or @ConfigurationProperties can be marked with @Profile to limit when it is loaded.
Spring概要文件提供了一种隔离应用程序配置部分的方法,并使其仅在某些环境中可用。任何@Component、@Configuration或@ConfigurationProperties都可以用@Profile标记,以限制其加载.
7.4 Logging
Spring Boot uses Commons Logging for all internal logging but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2, and Logback. In each case, loggers are pre-configured to use console output with optional file output also available.
Spring Boot使用Commons日志记录所有内部日志,但保留底层日志实现的打开状态。为Java Util日志记录、Log4J2和Logback提供了默认配置。在每种情况下,记录器都预先配置为使用控制台输出,还可以使用可选的文件输出。
By default, if you use the “Starters”, Logback is used for logging. Appropriate Logback routing is also included to ensure that dependent libraries that use Java Util Logging, Commons Logging, Log4J, or SLF4J all work correctly.
默认情况下,如果使用“启动器”,则使用Logback进行日志记录。还包括适当的Logback路由,以确保使用Java Util日志、Commons日志、Log4J或SLF4J的依赖库都能正常工作。
7.5 Internationalization
Spring Boot supports localized messages so that your application can cater to users of different language preferences. By default, Spring Boot looks for the presence of a messages resource bundle at the root of the classpath.
Spring Boot支持本地化消息,因此您的应用程序可以满足不同语言偏好的用户。默认情况下,SpringBoot在类路径的根目录下查找消息资源包的存在。
7.6 JSON
Spring Boot provides integration with three JSON mapping libraries:
- Gson
- Jackson
- JSON-B
Jackson is the preferred and default library
7.7 Developing Web Applications
Spring Boot is well suited for web application development. You can create a self-contained HTTP server by using embedded Tomcat, Jetty, Undertow, or Netty. Most web applications use the springboot-starter-web module to get up and running quickly. You can also choose to build reactive web applications by using the spring-boot-starter-webflux module.
Spring Boot非常适合web应用程序开发。您可以使用嵌入式Tomcat、Jetty、Undertow或Netty创建一个自包含的HTTP服务器。大多数web应用程序使用springboot starter web模块快速启动和运行。您还可以选择使用spring boot starter webflux模块构建反应式web应用程序。