Skip to content

Latest commit

 

History

History
320 lines (216 loc) · 17.8 KB

11.DevelopingYourFirstSpringBootApplication.md

File metadata and controls

320 lines (216 loc) · 17.8 KB

11. Developing Your First Spring Boot Application

11. 开发你的第一个Spring Boot应用程序

This section describles how to develop a simple "Hello World!" Web application that highlights some of Spring Boot's key features. We use Maven to build this project, since most IDEs support it.

这节描述了如何开发一个简单的“Hello World!”的Web应用程序,它强调了Spring Boot关键特性。由于大多数IDE都已经支持Maven,所以我们将使用Maven来构建这个项目。

Tip
小提示

The spring.io web site contains many "Getting Started" guides that use Spring Boot. If you need to solve a specific problem, check there first.

spring.io网站提供了很多使用Spring Boot的“入门”指南。如果你需要解决特定的问题时,你可以去这里看看。

You can shortcut the steps below by going to start.spring.io and choosing the "Web" starter from the dependencies searcher.Doing so generates a new project structure so that you can start coding right away. Check the Spring Initializr documentation for more details.

你可以到start.spring.io网站,并从依赖搜索器选择“Web”启动器来简化下面的步骤。 这是生成新的项目结构正确编码实践之路。可以从Spring初始化文档来获取详细的描述。

Before we begin, open a terminal and run the following commands to ensure that you have valid version of Java and Maven installed:

在我们开始前,先打开终端并运行下面正确的命令来检查你安装的Java和Maven版本是否正确。

$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot (TM) 64-Bit Server VM (build 25.102-b14, mixed mode)

$ mvn -v
Apache Maven 3.3.9
(bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T16:41:47+00:00)
Maven home : /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.8.0_102, vendor: Orcale Corporation
Note
说明

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.

这个例子需要创建它自己的目录。后面说明前提是你已经创建合适的目录,并且在这个目录里。

Creating the POM

创建POM

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

我们首先需要创建一个Maven的pom.xml文件。pom.xml文件是用于构建你的项目的处方。打开你的编辑器并将下面的内容添加到你的编辑器里:

<?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/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.1.RELEASE</version>
	</parent>

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

The preceding listing should give you a working build.You can test it by running mvn package (for now, you can ignore the "jar will be empty - no content was marked for inclusion!" warning).

从前述的列表里给我们提供了一个构建工作。你可以使用运行mvn包来测试它(现在,你可以忽略“jar will be empty - no content was marked for inclusion!”的警告)。

Note
说明

At this point, you could import the project into an IDE(most modern Java IDEs include built-in support for Maven).For simplicity, we continue to use a plain text editor for this example.

在这里例子里,你可以导入这个项目到你的IDE里(大多数现代的Java IDE包含了Maven内置支持)。简单的方式,我们将在这个例子里继续使用纯文本编辑器。

Adding Classpath Dependencies

添加Classpath依赖

Spring Boot provides a number of "starters" that let you 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提供了若干可以让你加入到classpat的“starter”。我们的例子应用程序已经在POM的父节点里使用了spring-boot-starter-parentspring-boot-starter-parent是一个提供非常有用的Maven默认值的特殊的starter。它也提供了关系依赖管理器章节来让你可以省略“blessed”依赖的版本标签。

Other "starters" provide dependencies that you are likely to need when developing a specific type of application. Since we are developing a web application, web add a spring-boot-starter-web dependency. Before that, we can look at what we currently have by running the following command:

其他的“starter”提供了你需要开发特殊类型的应用程序所需要的依赖关系。由于我们开发一个Web应用程序,因此web需要添加一个spring-boot-starter-web依赖项。在此之前,我们可以通过下面的命令来查看我们当前的功能:

$ mvn dependency:tree

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

The mvn dependency:tree command prints a tree representation of your dependencies. You can see that spring-boot-starter-parent provaides no dependencies by itself. To add the necessary dependencies, edit your pom.xml and the spring-boot-starter-web dependecy immediately below the parent section:

mvn dependency:tree命令打印了依赖性的树状图。你可以看到spring-boot-starter-parent本身并没有依赖关系。要添加必要的依赖关系,请在父节点编辑你的pom.xml并增加spring-boot-starter-web依赖关系:

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>

If you run mvn dependency:tree again, you see that there are now a number of additional dependencies, including the Tomcat web server and Spring Boot itself.

如果你再次运行mvn dependency:tree,你会发现一些列的其他的依赖包,包含Tomcat web服务器和Spring Boot本身。

Writing the Code

编写代码

To finish our application, we need to create a single Java file. By default, Maven compiles sources from src/main/java, so you need to create that folder structure and then add a file named src/main/java/Example.java to contain the following code:

要完成我们的应用程序,我们需要创建一个Java文件。默认情况下,Maven 编译源代码都是从src/main/java,所以你需要创建这个目录结构,然后添加一个名字为src/main/java/Example.java的文件,它的代码如下所示:

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
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 is not much code here, quite a lot is going on.We step through the important parts in the next few sections.

虽然没有太多的代码,但是我们还有很多事情正在进行。我们将在后续章节介绍更多重要的部分。

The @RestController and @RequestMapping Annotations

@RestController 和 @RequestMapping 注释

The first annotation on our Example class is @RestController. This is known as a stereotype annotation. It provides 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 considers it when handing incoming web requests.

@RestController是在我们这个例子里第一个注视。这是一个已知的一直沿用的注视。它为阅读代码的人们提供了线索,对Spring来说,它扮演了至关重要的角色。在这个例子里,我们的类是一个web @Controller,所以Spring在处理web请求时会考虑它们。

The @RequestMapping annotation provides "routing" information. It tells 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将结果字符串直接返回给调用者。

Tip

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

@RestController和@RequestMapping注释是Spring MVC的注释。(它们不是Spring Boot所特有的。)更多细节可以参考Spring参考文档的MVC章节。

The @EnableAutoConfiguration Annotation

@EnableAutoConfiguration注释

The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to "guess" how you 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 assumes that you are developing a web application and sets up 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 tow Concepts are not directly tied. You are free to pick an choose jar dependencies outside of the starters. Spring Boot still does its best to auto-configure your application

启动器和自动配置

自动配置旨在和“启动器”配合良好,但是两者概念上是不完全相等的。你可以自有的选择除启动器免费的依赖jar包。Spring Boot仍然可以非常好的自动配置你的应用程序。

The “main” Method

main入口方法

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 bootstraps our application, starting Spring, which, in turn, starts 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类会被调用。SpringApplication启动我们的应用程序,从Spring开始,然后开启自动配置的Tomcat web服务器。我们需要将Example.class作为参数传递给run方法,然后告知SpringApplication是Spring的主要组件。args参数数组将所有命令行参数也传递给run方法。

Running the Example

运行示例

At the point, your application should work. Since you used the spring-boot-starter-parent POM, you have a useful run goal that you can use to start the application. The mvn spring-boot:run from the root project directory to start the application. You should see output similar to the following:

现在,你的应用程序该运行了。自从你使用spring-boot-starter-parent POM,你就拥有了一个非常有用的run目标,你可以用它来启动应用程序。在你的项目目录下执行mvn spring-boot:run来启动你的应用程序。你将会看到类似输出入下面所示:

$ mvn spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.0.1.RELEASE)
....... . . .
....... . . . (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:

如果你打开浏览器访问localhost:8080, 你将看到如下面的输出:

Hello World!

To gracefully exit the application, press ctrl-c.

ctrl-c来退出应用程序。

Creating an Executable Jar

创建可执行Jar包

We 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文件来结束我们的示例。可执行的jar包(有时又称为“fat jars”)是一个包含已经编译的classes和代码运行需要jar依赖项的归档文件。

Executable jars and Java

可执行jars和Java

Java does not provide a standard to load nested jar files (jar files that are themselves contained within a jar). This can be problematic if you are looking to distribute a self-contained applicaion.

Java没有提供一个加载嵌套jar文件的标准(jar文件本身包含在一个jar里面)。如果你想分发一个自包含的应用程序,这可能会有问题。

To solve this problem, many developers use "uber" jars. An uber jar packages all the classes from all the application's dependencies into a single archive. To problem with this approach is that it becomes hard to see which libraries are in your application. It can also be problematic if the same filename is used (but with different content) in multiple jars.

为了解决这个问题,许多的开发者使用“uber”的jar包。uber jar包是将应用程序所依赖的所有classes文件的打包到一个独立的归档文件。如果有多个jar中使用了相同的文件名,这可能会有问题。

Spring Boot takes a different approach and lets you 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. To do so, insert the following lines just below the dependencies section:

要创建可执行jar包,我们需要添加spring-boot-maven-plugin到我们的pom.xml。具体做法,添加下面的代码到dependencies节点下面:

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>
Note
笔记

The spring-boot-starter-parent POM includes configuration to bind the repackage goal. If you do not use the parent POM, you need to declare this configuration yourself. See the plugin documentation for details.

spring-boot-starter-parent POM 包含了配置项去绑定重新打包的目标。如果你没有使用父POM,你需要自行声明次配置项。详细信息可以参考插件文档。

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

保存你的pom.xml文件,并在命令行运行mvn pacage命令,如下:

$ 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.1.RELEASE: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, as follows:

如果你看到target目录,你也许可以看到myproject-0.0.1-SNAPSHOT.jar。这个文件大约10MB大小。如果你想看看里面的内容,你可以使用jar tvf,如下:

$ 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。这个original jar 文件是Spring Boot在重新构建时由Maven创建的。

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

要运行应用程序,使用java -jar命令,如下:

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

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

As before, to exit the application, press ctrl-c.

和前面一样,按ctrl-c来退出应用程序。