References
Spring Boot 1.5: http://docs.spring.io/spring-boot/docs/1.5.x/reference/htmlsingle/#getting-started
前言
通读 Spring Boot 官方文档,当前最新 Release 版本是 1.5;摘录其核心论点,翻译,并做重要批注;
本文为作者的原创作品,转载需注明出处;
Part II. Getting Started
If you’re just getting started with Spring Boot, or ‘Spring’ in general, this is the section for you! Here we answer the basic “what?”, “how?” and “why?” questions. You’ll find a gentle introduction to Spring Boot along with installation instructions. We’ll then build our first Spring Boot application, discussing some core principles as we go.
【8】Introducing Spring Boot
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”. We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
开篇便描绘了 Spring Boot 的作用,使得创建标准的、具备产品化的基于 Spring 所构建的应用程序,而你需要做的仅仅是 “just run”;大多数 Spring Boot Applications 也仅仅需要少量的配置;
You can use Spring Boot to create Java applications that can be started using
java -jar
or more traditionalwar
deployments. We also provide acommand line
tool that runs “spring scripts”.
你可以使用java -jar
或者使用war
来启动 Spring Boot;同时也可以使用command line
来执行”spring scripts”;
Our primary goals are:
- Provide a radically faster and widely accessible getting started experience for all Spring development.
提供简单快速的开发 Spring 的机制。- Be opinionated out of the box, but get out of the way quickly as requirements start to diverge from the defaults.
可以快速的从 defaults 去定制;- Provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers, security, metrics, health checks, externalized configuration).
提供了一系列的 non-functional 功能,比如嵌入式的 servers, security,健康状态检查、metrics,可扩展配置等特性;- Absolutely no code generation and no requirement for XML configuration.
【9】 System Requirements
By default, Spring Boot 1.5.2.RELEASE requires Java 7 and Spring Framework 4.3.7.RELEASE or above. You can use Spring Boot with Java 6 with some additional configuration. See Section 84.11, “How to use Java 6” for more details. Explicit build support is provided for Maven (3.2+), and Gradle 2 (2.9 or later) and 3.
Although you can use Spring Boot with Java 6 or 7, we generally recommend Java 8 if at all possible.
【10】 Installing Spring Boot
Spring Boot can be used with “classic” Java development tools or installed as a command line tool. Regardless, you will need Java SDK v1.6 or higher. You should check your current Java installation before you begin:
1 | java -version |
【10.1】 Installation instructions for the Java developer
You can use Spring Boot in the same way as any standard Java library. Simply include the appropriate
spring-boot-*.jar
files on your classpath. Spring Boot does not require any special tools integration, so you can use any IDE or text editor; and there is nothing special about a Spring Boot application, so you can run and debug as you would any other Java program.
你可以将 Spring Boot 当做一个普通的 jar 来使用;
Although you could just copy Spring Boot jars, we generally recommend that you use a build tool that supports dependency management (such as Maven or Gradle).
【10.1.1】 Maven installation
Spring Boot is compatible with Apache Maven 3.2 or above. If you don’t already have Maven installed you can follow the instructions at maven.apache.org.
[Tip]
On many operating systems Maven can be installed via a package manager. If you’re an OSX Homebrew user try brew install maven. Ubuntu users can runsudo apt-get install maven
.
Spring Boot dependencies use the
org.springframework.boot
groupId. Typically your Maven POM file will inherit from thespring-boot-starter-parent
project and declare dependencies to one or more “Starters”. Spring Boot also provides an optional Maven plugin to create executable jars.
Spring Boot 的依赖使用 groupId org.springframework.boot
作为标识;典型的,你的 Maven POM 文件可以继承自 spring-boot-starter-parent project,然后通过 Starters 来声明 dependencies;同样,Spring Boot 也提供了额外的 Maven plugin 来创建可执行的 jars;
pom.xml1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<!-- Add typical dependencies for a web application -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!-- Package as an executable jar -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
[Tip]
Thespring-boot-starter-parent
is a great way to use Spring Boot, but it might not be suitable all of the time. Sometimes you may need to inherit from a different parent POM, or you might just not like our default settings. See Section 13.2.2, “Using Spring Boot without the parent POM” for an alternative solution that uses animport
scope.
【10.1.2】 Gradle installation
【10.2】 Installing the Spring Boot CLI
The Spring Boot CLI is a command line tool that can be used if you want to quickly prototype with Spring. It allows you to run Groovy scripts, which means that you have a familiar Java-like syntax, without so much boilerplate code.
可以使用 Spring Boot CLI (Spring Boot 的命令行工具)来快速构建 Spring Boot 原型;它允许你使用 Groovy 脚本来进行构建;
You don’t need to use the CLI to work with Spring Boot but it’s definitely the quickest way to get a Spring application off the ground.
【10.2.1】 Manual installation
You can download the Spring CLI distribution from the Spring software repository:
Cutting edge snapshot distributions are also available.
Once downloaded, follow the INSTALL.txt instructions from the unpacked archive. In summary: there is a spring script (spring.bat for Windows) in a bin/ directory in the .zip file, or alternatively you can use java -jar with the .jar file (the script helps you to be sure that the classpath is set correctly).
下载完成以后,通过 INSTALL.txt 的提示进行安装;
【10.2.2】 Installation with SDKMAN!
SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions of various binary SDKs, including Groovy and the Spring Boot CLI. Get SDKMAN! from sdkman.io and install Spring Boot with
SDKMAN 可以用来管理多个版本不同的 SDKs,包括 Groovy 以及 Spring Boot CLI;你可以通过 SDKMAN 使用如下的命令行来安装 Spring Boot;
1 | $ sdk install springboot |
If you are developing features for the CLI and want easy access to the version you just built, follow these extra instructions.
如果你想通过 CLI 开发一些属性并且想非常容易的进入你所构建的版本,使用如下的命令,1
2
3
4$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-1.5.2.RELEASE-bin/spring-1.5.2.RELEASE/
$ sdk default springboot dev
$ spring --version
Spring CLI v1.5.2.RELEASE
This will install a local instance of
spring
called the dev instance. It points at your target build location, so every time you rebuild Spring Boot, spring will be up-to-date.
上面的额命令将会安装一个本地的名为 dev 的 spring
实例,并且它将会指向目标的构建路径;
You can see it by doing this:
1 | $ sdk ls springboot |
【10.2.3】 OSX Homebrew installation
If you are on a Mac and using Homebrew, all you need to do to install the Spring Boot CLI is:
1 | $ brew tap pivotal/tap |
Homebrew will install spring
to /usr/local/bin
.
【10.2.4】 MacPorts installation
If you are on a Mac and using MacPorts, all you need to do to install the Spring Boot CLI is:
1 | $ sudo port install spring-boot-cli |
【10.2.5】 Command-line completion
Spring Boot CLI ships with scripts that provide command completion for BASH and zsh shells. You can
source
the script (also namedspring
) in any shell, or put it in your personal or system-wide bash completion initialization. On a Debian system the system-wide scripts are in/shell-completion/bash
and all scripts in that directory are executed when a new shell starts. To run the script manually, e.g. if you have installed using SDKMAN!
1 | $ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring |
[Note]
If you install Spring Boot CLI using Homebrew or MacPorts, the command-line completion scripts are automatically registered with your shell.
如果你使用 Homebrew 或者是 MacPorts 安装的 Spring Boot CLI,那么 command-line completion scripts 将会自动的在你的 shell 中注册;
【10.2.6】 Quick start Spring CLI example
Here’s a really simple web application that you can use to test your installation. Create a file called
app.groovy
:
1 |
|
Then simply run it from a shell:
1 | $ spring run app.groovy |
[Note]
It will take some time when you first run the application as dependencies are downloaded. Subsequent runs will be much quicker.
Open localhost:8080 in your favorite web browser and you should see the following output:
1 | Hello World! |
【10.3】 Upgrading from an earlier version of Spring Boot
If you are upgrading from an earlier release of Spring Boot check the “release notes” hosted on the project wiki. You’ll find upgrade instructions along with a list of “new and noteworthy” features for each release.
To upgrade an existing CLI installation use the appropriate package manager command (for example
brew upgrade
) or, if you manually installed the CLI, follow the standard instructions remembering to update your PATH environment variable to remove any older references.
【11】 Developing your first Spring Boot application
Let’s develop a simple “Hello World!” web application in Java that highlights some of Spring Boot’s key features. We’ll use Maven to build this project since most IDEs support it.
[Tip]
The spring.io web site contains many “Getting Started” guides that use Spring Boot. If you’re looking to solve a specific problem; check there first.
You can shortcut the steps below by going to start.spring.io and choosing theweb starter
from the dependencies searcher. This will automatically generate a new project structure so that you can start coding right away. Check the documentation for more details.
Before we begin, open a terminal to check that you have valid versions of Java and Maven installed.
1 | $ java -version |
1 | $ mvn -v |
【11.1】 Creating the POM
We need to start by creating a Maven
pom.xml
file. Thepom.xml
is the recipe that will be used to build your project. Open your favorite text editor and add the following:
1 |
|
This should give you a working build, you can test it out by running
mvn package
(you can ignore the “jar will be empty - no content was marked for inclusion!” warning for now).
使用mvn package
命令构建项目;
[Note]
At this point you could import the project into an IDE (most modern Java IDE’s include built-in support for Maven). For simplicity, we will continue to use a plain text editor for this example.
然后,你可以将此项目导入 IDE;
【11.2】 Adding classpath dependencies
Spring Boot provides a number of “Starters” that make easy to add jars to your classpath. Our sample application has already used
spring-boot-starter-parent
in the parent section of the POM. Thespring-boot-starter-parent
is a special starter that provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for “blessed” dependencies.
Spring Boot 提供了一系列的 “Starters”,可以帮助你将 jars 添加到你的 classpath 中;我们的用例中在父类定义的 section 中使用到了spring-boot-starter-parent
,spring-boot-starter-parent
是一个特殊的 starter 元素并且提供了相关的默认的 Maven 配置;
Other “Starters” simply provide dependencies that you are likely to need when developing a specific type of application. Since we are developing a web application, we will add a
spring-boot-starter-web
dependency — but before that, let’s look at what we currently have.
开发 web application,所以我们会使用到spring-boot-starter-web
依赖;但是在我们这样做之前,看看我们当前所有的依赖,
1 | $ mvn dependency:tree |
The
mvn dependency:tree
command prints a tree representation of your project dependencies. You can see thatspring-boot-starter-parent
provides no dependencies by itself. Let’s edit our pom.xml and add the spring-boot-starter-web dependency just below the parent section:
1 | <dependencies> |
If you run
mvn dependency:tree
again, you will see that there are now a number of additional dependencies, including the Tomcat web server and Spring Boot itself.
再次执行 mvn dependency:tree
,你将会看到与 web application 相关的 dependencies;
【11.3】 Writing the code
To finish our application we need to create a single Java file. Maven will compile sources from
src/main/java
by default so you need to create that folder structure, then add a file namedsrc/main/java/Example.java
:
1 | import org.springframework.boot.*; |
Although there isn’t much code here, quite a lot is going on. Let’s step through the important parts.
The @RestController and @RequestMapping annotations
The first annotation on our
Example
class is@RestController
. This is known as a stereotype annotation. It provides hints for people reading the code, and for Spring, that the class plays a specific role. In this case, our class is a web@Controller
so Spring will consider it when handling incoming web requests.
@RestController 提供 rest 风格的 Controller
The
@RequestMapping
annotation provides “routing” information. It is telling Spring that any HTTP request with the path “/” should be mapped to thehome
method. The@RestController
annotation tells Spring to render the resulting string directly back to the caller.
@RequestMapping
注解提供了路由的信息;将访问路径定位到 controller;
【11.3.2】 The @EnableAutoConfiguration annotation
The second class-level annotation is
@EnableAutoConfiguration
. This annotation tells Spring Boot to “guess” how you will want to configure Spring, based on the jar dependencies that you have added. Sincespring-boot-starter-web
added Tomcat and Spring MVC, the auto-configuration will assume that you are developing a web application and setup Spring accordingly.
@EnableAutoConfiguration
告诉 Spring Boot 如何配置;
Starters and Auto-Configuration
Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied. You are free to pick-and-choose jar dependencies outside of the starters and Spring Boot will still do its best to auto-configure your application.
Auto-configuration 被设计用来与 Starters 更好的协作,但是这两个概念并不是耦合在一起的;你可以在 starters 之外选择并获取 jar 依赖,Spring Boot 同样可以很好的自动的配置应用;
【11.3.3】 The “main” method
The final part of our application is the
main
method. This is just a standard method that follows the Java convention for an application entry point. Ourmain
method delegates to Spring Boot’sSpringApplication
class by calling run.SpringApplication
will bootstrap our application, starting Spring which will in turn start the auto-configured Tomcat web server. We need to passExample.class
as an argument to therun
method to tellSpringApplication
which is the primary Spring component. Theargs
array is also passed through to expose any command-line arguments.
最后一部分是main
方法,该方法中将会使用到SpringApplication
,SpringApplication
将会启动我们的应用,然后 Spring 容器随之启动,并自启动和配置 Tomcat web server….
【11.4】 Running the example
At this point our application should work. Since we have used the
spring-boot-starter-parent
POM we have a usefulrun
goal that we can use to start the application. Typemvn spring-boot:run
from the root project directory to start the application:
直接使用mvn spring-boot:run
就可以启动我们的应用;
1 | $ mvn spring-boot:run |
If you open a web browser to localhost:8080 you should see the following output:
1 | Hello World! |
To gracefully exit the application hit
ctrl-c
.
【11.5】 Creating an executable jar
Let’s finish our example by creating a completely self-contained executable jar file that we could run in production. Executable jars (sometimes called “fat jars”) are archives containing your compiled classes along with all of the jar dependencies that your code needs to run.
让我们通过创建一个完整的 self-contained executable jar 文件,可以在 production 中执行的文件;Executable jars (有时候被称作 “fat jars” ) 是一种归档文件,包含了你的编译文件(classes)以及一系列的所依赖的 jar 文件;
Executable jars and Java
Java does not provide any standard way to load nested jar files (i.e. jar files that are themselves contained within a jar). This can be problematic if you are looking to distribute a self-contained application.
Java 并没有提供任何标注的方式去加载内嵌的 jar 文件( 一个 jar 文件自身包含多个 jar 文件 );因为缺乏标准,所以,如果在你的程序中去读取第三方的 self-contained application 中的 jar 中的 jar 文件会存在种种问题;
To solve this problem, many developers use “uber” jars. An uber jar simply packages all classes, from all jars, into a single archive. The problem with this approach is that it becomes hard to see which libraries you are actually using in your application. It can also be problematic if the same filename is used (but with different content) in multiple jars.
为了解决这些问题,许多开发者使用“uber” jars;一个 uber jar 只是简单的把所有的 jars 文件中的 classes 文件打包到一个归档文件中;但是,使用这种方式的最大问题在于,你无法得知 libraries 的信息以及你到底使用到了哪些 libraries;当然还有一个问题,如果有相同文件名(包名也相同)那么会被相互覆盖掉;
Spring Boot takes a different approach and allows you to actually nest jars directly.
因此 Spring Boot 提供了一个不同的方式来处理内嵌的 jars;如下所述;
To create an executable jar we need to add the
spring-boot-maven-plugin
to ourpom.xml
. Insert the following lines just below thedependencies
section:
创建一个 executable jar, 我们需要将spring-boot-maven-plugin
加入pom.xml
,
1 | <build> |
[Note]
Thespring-boot-starter-parent
POM includes<executions>
configuration to bind the repackage goal. If you are not using the parent POM you will need to declare this configuration yourself. See the plugin documentation for details.
注意,spring-boot-starter-parent
包含了与 repackage goal 相关的<executions>
的配置;如果你没有使用 parent POM,那么你将需要手动的去声明,See the plugin documentation for details.
Save your
pom.xml
and runmvn package
from the command line:
1 | $ mvn package |
If you look in the
target
directory you should seemyproject-0.0.1-SNAPSHOT.jar
. The file should be around 10 MB in size. If you want to peek inside, you can usejar tvf
:
myproject-0.0.1-SNAPSHOT.jar
就是被打包好的可被执行的 jar,executive jar;可以通过命令jar tvf
查看该 jar 的内部信息;
1 | $ jar tvf target/myproject-0.0.1-SNAPSHOT.jar |
You should also see a much smaller file named
myproject-0.0.1-SNAPSHOT.jar.original
in thetarget
directory. This is the original jar file that Maven created before it was repackaged by Spring Boot.
myproject-0.0.1-SNAPSHOT.jar.original
就是原始的 jar 包;
To run that application, use the
java -jar
command:
然后,你可以通过java -jar
命令去执行该 executive jar;
1 | $ java -jar target/myproject-0.0.1-SNAPSHOT.jar |
As before, to gracefully exit the application hit
ctrl-c
.
【12】 What to read next
Hopefully this section has provided you with some of the Spring Boot basics, and got you on your way to writing your own applications. If you’re a task-oriented type of developer you might want to jump over to spring.io and check out some of the getting started guides that solve specific “How do I do that with Spring” problems; we also have Spring Boot-specific How-to reference documentation.
The Spring Boot repository has also a bunch of samples you can run. The samples are independent of the rest of the code (that is you don’t need to build the rest to run or use the samples).
Otherwise, the next logical step is to read Part III, “Using Spring Boot”. If you’re really impatient, you could also jump ahead and read about Spring Boot features.