# 20190608 spring-boot | part2(11~12)

Spring Boot Reference Guide
2.1.5.RELEASE
https://docs.spring.io/spring-boot/docs/2.1.5.RELEASE/reference/htmlsingle/#getting-started-first-application

# 11. Developing Your First Spring Boot Application

This section describes 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.

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

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

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 is used to build your project. Open your favorite text editor and add the following:

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

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.

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.

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

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. To add the necessary dependencies, edit your pom.xml and add the spring-boot-starter-web dependency immediately below the parent section:

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.

## 11.3 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:

Although there is not much code here, quite a lot is going on. We step through the important parts in the next few sections.

### 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 considers it when handling incoming web requests.

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.

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.

### 11.3.2 The @EnableAutoConfiguration Annotation

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.

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. Spring Boot still does its best to auto-configure your application.

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

## 11.4 Running the Example

At this 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. Type mvn spring-boot:run from the root project directory to start the application. You should see output similar to the following:

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

To gracefully exit the application, press ctrl-c.

## 11.5 Creating an Executable 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.

Executable jars and Java
\
Java does not provide a standard way 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 application.
\
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. The 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.
\
Spring Boot takes a different approach and lets you actually nest jars directly.

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:

The spring-boot-starter-parent POM includes <executions> 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.

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

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:

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.

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

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

# 12. What to Read Next

Hopefully, this section provided some of the Spring Boot basics and got you on your way to writing your own applications. If you are 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] also has a [bunch of samples] you can run. The samples are independent of the rest of the code (that is, you do not 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 are really impatient, you could also jump ahead and read about [Spring Boot features.]

# 11 开发你的第一个 Spring Boot 应用

## 11.2 添加 ClassPath 依赖项

Spring Boot 添加了许多（a number of）“启动器” 允许你添加 jars 到你的类路径下。我们的示例应用程序已经在POM的父节中使用了spring-boot-starter-parent。spring-boot-starters-parent 是一个特殊的启动器，它提供了可用的 maven 默认配置。它同样提供一个 dependency-management 节点以便（so that）你可以省略（omit）version “blessed”依赖项的版本标签。

mvn dependency:tree 命令打印输来表示（representation）你项目依赖。您可以看到 spring-boot-starter-parent 本身（itself）不提供依赖关系。要添加必要（necessary）的依赖，编辑你的 pom.xml， 添加 spring-boot-starters-web 依赖紧接（immediately）与 parent 节点之下（below）。

## 11.3 编写代码

### 11.3.1 @RestController 和 @RequestMapping 注解

@RequestMapping@RestController 注解是 Spring MVC 注解。（他们不是 Spring Boot 特有的），更多详情请查看 Spring 参考文档的 MVC 章节

## 11.5 创建可执行 jar

java 没有提供标准的方式去加载嵌套的 jar 文件（java 文件本身(themsevles)在 jar 里面(within)）。如果你要分发自包含的应用，将会造成一些问题（problematic）。
\

\
Spring Boot 用不同的方法，让你直接嵌套 jars

要创建一个可执行 jar，我们需要添加 spring-boot-maven-plugin 到你的 pom.xml。这样做，插入以下行紧接着 denpendency 节点：

spring-boot-maven-plugin POM 包含了 <excutions> 配置绑定到 repackage 目标。如果你不使用父 POM，你需要定义你自己的这个配置项。查看 插件文档 获得更多详情。