文章作者: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開發(fā)一個簡單的Web應(yīng)用“Hello World!”闲先,通過應(yīng)用來強調(diào)Spring Boot的一些關(guān)鍵特性赖钞。由于大多數(shù)IDE都支持Maven,因此我們用Maven來構(gòu)建這個項目合瓢。
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網(wǎng)站上有許多使用Spring Boot的“Getting Started”指南偎蘸。如果你要解決一個特定的問題;先去網(wǎng)站上看一下。
你可以通過到start.spring.io上并從依賴搜索器中選擇
web
啟動器來簡化下面的步驟嫩絮。這會自動的產(chǎn)生一個新的工程結(jié)構(gòu)所以你能以正確的方式開始編碼丛肢。更多細節(jié)請看文檔。
Before we begin, open a terminal to check that you have valid versions of Java and Maven installed.
在開始之前剿干,打開終端檢查一下蜂怎,確保你已經(jīng)安裝了合適的Java版本和Maven版本。
$ 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)
$ 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”.
這個例子需要創(chuàng)建它自己的文件夾置尔。接下來的介紹假設(shè)你已經(jīng)創(chuàng)建了合適的文件夾并且文件夾是你的當前目錄杠步。
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:
我們首先需要創(chuàng)建一個Maven的pom.xml
文件。pom.xml
是用來構(gòu)建項目的處方榜轿。打開你最喜歡的文本編輯器并添加以下內(nèi)容:
<?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).
這應(yīng)該給你一個工作幽歼,你可以通過運行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中(大多數(shù)Java IDE都有對Maven的內(nèi)置支持)谬盐。為了簡便甸私,在這個例子中我們將繼續(xù)使用普通的文本編輯器。
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包皇型。我們的例子程序已經(jīng)在POM的parent
部分使用了spring-boot-starter-parent
。spring-boot-starter-parent
是一個特別的啟動器助析,它能提供有用的Maven默認設(shè)置犀被。它也提供了依賴管理部分,因此你可以對“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.
當開發(fā)一個特定的應(yīng)用時寡键,其它的“Starters”簡單的提供了你可能需要的依賴。由于我們正在開發(fā)一個web應(yīng)用雪隧,我們將添加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 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
依賴:
<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服務(wù)器和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
:
為了完成我們的應(yīng)用,我們需要創(chuàng)建一個簡單的Java文件措近。Maven默認的將從src/main/java
編譯源碼溶弟,因此你需要創(chuàng)建文件結(jié)構(gòu),然后添加名為src/main/java/Example.java
的文件:
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.
盡管這兒沒有太多代碼瞭郑,但已經(jīng)發(fā)生了許多事情辜御。讓我們一步步瀏覽這些重要的部分。
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而言,這個類有一個特定的任務(wù)碳抄。在這個例子中愉老,我們的類是一個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請求應(yīng)該映射到home
方法上贱鄙。@RestController
注解告訴Spring將結(jié)果渲染成字符串形式并直接返回給調(diào)用者劝贸。
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特有的)。更多細節(jié)請看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瞎颗,自動配置會假設(shè)你正在開發(fā)一個web應(yīng)用并相應(yīng)的設(shè)置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.
啟動器和自動化配置
自動配置被設(shè)計成跟『啟動器』能一起工作的很好,但這兩個概念沒有直接聯(lián)系哼拔。你可以自由的挑選啟動器之外的jar依賴引有,Spring Boot仍會最大程度地自動配置你的應(yīng)用。
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應(yīng)用程序入口規(guī)范的標準方法譬正。main
方法中委托Spring Boot的SpringApplication
類調(diào)用run
方法。SpringApplication
將引導我們的應(yīng)用啟動Spring檬姥,Spring將啟動自動配置的Tomcat web服務(wù)器曾我。我們需要將Example.class
作為參數(shù)傳給run
方法,告訴SpringApplication
它是主要的Spring組件健民。args
數(shù)組會將所有命令行參數(shù)傳給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:
此時我們的應(yīng)用應(yīng)該工作了。既然我們已經(jīng)使用了spring-boot-starter-parent
POM秉犹,那我們有一個有用的run
目標蛉谜,我們使用它來啟動應(yīng)用。在工程的根目錄中輸入mvn spring-boot:run
來啟動應(yīng)用崇堵。
$ 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
,你應(yīng)該會看到下面的輸出筑辨。
Hello World!
To gracefully exit the application hit ctrl-c
.
可以點擊ctrl-c
退出應(yīng)用。
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.
通過創(chuàng)建一個在產(chǎn)品中能運行的完整的自包含可執(zhí)行jar文件來結(jié)束我們的例子幸逆」髟可執(zhí)行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中)楚昭。如果你想分發(fā)一個自包含的應(yīng)用栖袋,這可能是個問題。
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.
為了解決這個問題抚太,許多開發(fā)者使用“uber” jars塘幅。uber jar簡單的將所有jars的所有類打包到一個單獨的存檔文件中。這個方法的問題是很難看到你的應(yīng)用正在使用的是哪個庫尿贫。如果多個jars使用了相同的文件名(不同的內(nèi)容)也是個問題电媳。
Spring Boot takes a different approach and allows you to actually nest jars directly.
Spring Boot采用了一種不同的方法來處理這個問題,允許你真正的直接內(nèi)嵌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:
為了創(chuàng)建可執(zhí)行jar匾乓,我們需要添加spring-boot-maven-plugin
到pom.xml
中。在dependencies
部分下面插入以下內(nèi)容:
<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 therepackage
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拼缝,那你需要自己聲明這個配置。更多細節(jié)請看插件文檔彰亥。
Save your pom.xml
and run mvn package
from the command line:
保存你的pom.xml
并從命令行中運行mvn package
:
$ 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
你應(yīng)該看到myproject-0.0.1-SNAPSHOT.jar
咧七。這個文件大小應(yīng)該在10 Mb左右。如果你想看里面的內(nèi)容任斋,你可以使用: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
目錄中應(yīng)該也能看到一個更小的名為myproject-0.0.1-SNAPSHOT.jar.original
的文件继阻。這是Spring Boot repackage之前Maven創(chuàng)建的最初的jar文件。
To run that application, use the java -jar
command:
為了運行這個應(yīng)用仁卷,要使用java -jar
命令:
$ 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
來退出應(yīng)用。
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.
希望這部分內(nèi)容給你提供了一些Spring Boot的基本知識锦积,讓你寫了你自己的應(yīng)用芒帕。如果你是一個面向任務(wù)的開發(fā)人員,你可能想跳到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也有一些你可以運行的例子哮幢。例子是獨立于其它代碼的(運行或使用例子時你不需要構(gòu)建其它的內(nèi)容)带膀。
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的特性敛纲。