Spring Boot 2.0.0参考手册_中英文对照_Part II_11-12

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

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.

我们用Java开发一个简单的Web应用“Hello World!”,通过应用来强调Spring Boot的一些关键特性。由于大多数IDE都支持Maven,因此我们用Maven来构建这个项目。

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 the web starter from the dependencies searcher. This will automatically generate a new project structure so that you can start coding right the way. Check the documentation for more details.

 

spring.io网站上有许多使用Spring Boot的“Getting Started”指南。如果你要解决一个特定的问题;先去网站上看一下。

你可以通过到start.spring.io上并从依赖搜索器中选择web启动器来简化下面的步骤。这会自动的产生一个新的工程结构所以你能以正确的方式开始编码。更多细节请看文档。

Before we begin, open a terminal to check that you have valid versions of Java and Maven installed.

在开始之前,打开终端检查一下,确保你已经安装了合适的Java版本和Maven版本。

1
2
3
4
$ java -version
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
1
2
3
4
$ mvn -v
Apache Maven 3.2.3 (33f8c3e1027c3ddde99d3cdebad2656a31e8fdf4; 2014-08-11T13:58:10-07:00)
Maven home: /Users/user/tools/apache-maven-3.1.1
Java version: 1.7.0_51, vendor: Oracle Corporation

This sample needs to be created in its own folder. Subsequent instructions assume that you have created a suitable folder and that it is your “current directory”.

 

这个例子需要创建它自己的文件夹。接下来的介绍假设你已经创建了合适的文件夹并且文件夹是你的当前目录。

11.1 Creating the POM

We need to start by creating a Maven pom.xml file. The pom.xml is the recipe that will be used to build your project. Open your favorite text editor and add the following:

我们首先需要创建一个Maven的pom.xml文件。pom.xml是用来构建项目的处方。打开你最喜欢的文本编辑器并添加以下内容:

1
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
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8"?>
<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>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
</parent>

<!-- Additional lines to be added here... -->

<!-- (you don't need this if you are using a .RELEASE version) -->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>

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来测试一下(你可以忽略警告“jar will be empty - no content was marked for inclusion!”)。

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中(大多数Java IDE都有对Maven的内置支持)。为了简便,在这个例子中我们将继续使用普通的文本编辑器。

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. The spring-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”,这样可以很容器的在classpath中添加jar包。我们的例子程序已经在POM的parent部分使用了spring-boot-starter-parentspring-boot-starter-parent是一个特别的启动器,它能提供有用的Maven默认设置。它也提供了依赖管理部分,因此你可以对“blessed”依赖忽略其版本标签。

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.

当开发一个特定的应用时,其它的“Starters”简单的提供了你可能需要的依赖。由于我们正在开发一个web应用,我们将添加spring-boot-starter-web依赖——但在那之前,让我们先看一下目前有什么。

1
2
3
$ mvn dependency:tree

[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT

The mvn dependency:tree command prints a tree representation of your project dependencies. You can see that spring-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:

mvn dependency:tree命令将你的工程依赖打印成一棵树的形式。你可以看到spring-boot-starter-parent本身没有提供依赖。让我们编辑pom.xml文件并parent部分添加spring-boot-starter-web依赖:

1
2
3
4
5
6
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</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,你将看到许多额外的依赖,包括Tomcat服务器和Spring Boot本身。

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 named src/main/java/Example.java:

为了完成我们的应用,我们需要创建一个简单的Java文件。Maven默认的将从src/main/java编译源码,因此你需要创建文件结构,然后添加名为src/main/java/Example.java的文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

@RequestMapping("/")
String home() {
return "Hello World!";
}

public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}

}

Although there isn’t much code here, quite a lot is going on. Let’s step through the important parts.

尽管这儿没有太多代码,但已经发生了许多事情。让我们一步步浏览这些重要的部分。

11.3.1 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.

Example类中的第一个注解是@RestController。这是一个模式化的注解。它为阅读代码的人提供了暗示,对于Spring而言,这个类有一个特定的任务。在这个例子中,我们的类是一个web @Controller,当web请求到来时,Spring会考虑用它来处理。

The @RequestMapping annotation provides “routing” information. It is telling Spring that any HTTP request with the path “/” should be mapped to the home method. The @RestController annotation tells Spring to render the resulting string directly back to the caller.

@RequestMapping注解提供了『路由』信息。它告诉Spring任何带有路径”/“的HTTP请求应该映射到home方法上。@RestController注解告诉Spring将结果渲染成字符串形式并直接返回给调用者。

The @RestController and @RequestMapping annotations are Spring MVC annotations (they are not specific to Spring Boot). See the MVC section in the Spring Reference Documentation for more details.

 
@RestController@RequestMapping是Spring MVC注解(它们不是Spring Boot特有的)。更多细节请看Spring参考文档中MVC部分。

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. Since spring-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基于你添加的jar依赖去”猜”你想怎样配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,自动配置会假设你正在开发一个web应用并相应的设置Spring。

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.

启动器和自动化配置

自动配置被设计成跟『启动器』能一起工作的很好,但这两个概念没有直接联系。你可以自由的挑选启动器之外的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. Our main method delegates to Spring Boot’s SpringApplication 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 pass Example.class as an argument to the run method to tell SpringApplication which is the primary Spring component. The args array is also passed through to expose any command-line arguments.

程序的最后部分是main方法。这是一个符合Java应用程序入口规范的标准方法。main方法中委托Spring Boot的SpringApplication类调用run方法。SpringApplication将引导我们的应用启动Spring,Spring将启动自动配置的Tomcat web服务器。我们需要将Example.class作为参数传给run方法,告诉SpringApplication它是主要的Spring组件。args数组会将所有命令行参数传给run方法。

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 useful run goal that we can use to start the application. Type mvn spring-boot:run from the root project directory to start the application:

此时我们的应用应该工作了。既然我们已经使用了spring-boot-starter-parent POM,那我们有一个有用的run目标,我们使用它来启动应用。在工程的根目录中输入mvn spring-boot:run来启动应用。

1
2
3
4
5
6
7
8
9
10
11
12
13
$ mvn spring-boot:run

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.BUILD-SNAPSHOT)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.222 seconds (JVM running for 6.514)

If you open a web browser to localhost:8080 you should see the following output:

如果你打开一个web浏览器,输入localhost:8080,你应该会看到下面的输出。

1
Hello World!

To gracefully exit the application hit ctrl-c.

可以点击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.

通过创建一个在产品中能运行的完整的自包含可执行jar文件来结束我们的例子。可执行jars(有时称为“fat jars”)是包含编译的类和代码运行需要的所有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中)。如果你想分发一个自包含的应用,这可能是个问题。

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的所有类打包到一个单独的存档文件中。这个方法的问题是很难看到你的应用正在使用的是哪个库。如果多个jars使用了相同的文件名(不同的内容)也是个问题。

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 our pom.xml. Insert the following lines just below the dependencies section:

为了创建可执行jar,我们需要添加spring-boot-maven-pluginpom.xml中。在dependencies部分下面插入以下内容:

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

The spring-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 POM包含绑定repackage目标的<executions>配置。如果你没有使用父POM,那你需要自己声明这个配置。更多细节请看插件文档。

Save your pom.xml and run mvn package from the command line:

保存你的pom.xml并从命令行中运行mvn package

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ mvn package

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.0.0.BUILD-SNAPSHOT:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

If you look in the target directory you should see myproject-0.0.1-SNAPSHOT.jar. The file should be around 10 Mb in size. If you want to peek inside, you can use jar tvf:

如果你看一下目录target你应该看到myproject-0.0.1-SNAPSHOT.jar。这个文件大小应该在10 Mb左右。如果你想看里面的内容,你可以使用:jar tvf

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 the target directory. This is the original jar file that Maven created before it was repackaged by Spring Boot.

你在target目录中应该也能看到一个更小的名为myproject-0.0.1-SNAPSHOT.jar.original的文件。这是Spring Boot repackage之前Maven创建的最初的jar文件。

To run that application, use the java -jar command:

为了运行这个应用,要使用java -jar命令:

1
2
3
4
5
6
7
8
9
10
11
12
13
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.BUILD-SNAPSHOT)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.536 seconds (JVM running for 2.864)

As before, to gracefully exit the application hit ctrl-c.

像前面一样,通过点击ctrl-c来退出应用。

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.

希望这部分内容给你提供了一些Spring Boot的基本知识,让你写了你自己的应用。如果你是一个面向任务的开发人员,你可能想跳到spring.io,找出一些getting started指南来解决特定的『用Spring怎样做』的问题;我们也提供了Spring Boot的How-to参考文档。

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).

Spring Boot repository也有一些你可以运行的例子。例子是独立于其它代码的(运行或使用例子时你不需要构建其它的内容)。

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.

此外,按逻辑接下来是读第三部分,『使用Spring Boot』。如果你真的不耐烦,你也跳过这部分,直接阅读Spring Boot的特性。

如果有收获,可以请我喝杯咖啡!