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開發(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-parentspring-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-pluginpom.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 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拼缝,那你需要自己聲明這個配置。更多細節(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的特性敛纲。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末淤翔,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子佩谷,更是在濱河造成了極大的恐慌,老刑警劉巖谐檀,帶你破解...
    沈念sama閱讀 206,839評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件抡谐,死亡現(xiàn)場離奇詭異,居然都是意外死亡稚补,警方通過查閱死者的電腦和手機童叠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,543評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來课幕,“玉大人厦坛,你說我怎么就攤上這事≌Ь” “怎么了杜秸?”我有些...
    開封第一講書人閱讀 153,116評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長润绎。 經(jīng)常有香客問我撬碟,道長,這世上最難降的妖魔是什么莉撇? 我笑而不...
    開封第一講書人閱讀 55,371評論 1 279
  • 正文 為了忘掉前任呢蛤,我火速辦了婚禮,結(jié)果婚禮上棍郎,老公的妹妹穿的比我還像新娘其障。我一直安慰自己,他們只是感情好涂佃,可當我...
    茶點故事閱讀 64,384評論 5 374
  • 文/花漫 我一把揭開白布励翼。 她就那樣靜靜地躺著,像睡著了一般辜荠。 火紅的嫁衣襯著肌膚如雪汽抚。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,111評論 1 285
  • 那天伯病,我揣著相機與錄音造烁,去河邊找鬼。 笑死,一個胖子當著我的面吹牛惭蟋,可吹牛的內(nèi)容都是我干的叠纹。 我是一名探鬼主播,決...
    沈念sama閱讀 38,416評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼敞葛,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了与涡?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,053評論 0 259
  • 序言:老撾萬榮一對情侶失蹤氨肌,失蹤者是張志新(化名)和其女友劉穎酌畜,沒想到半個月后桥胞,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,558評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,007評論 2 325
  • 正文 我和宋清朗相戀三年伊群,在試婚紗的時候發(fā)現(xiàn)自己被綠了舰始。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片咽袜。...
    茶點故事閱讀 38,117評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡酬蹋,死狀恐怖范抓,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情僧鲁,我是刑警寧澤寞秃,帶...
    沈念sama閱讀 33,756評論 4 324
  • 正文 年R本政府宣布春寿,位于F島的核電站绑改,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏识腿。R本人自食惡果不足惜渡讼,卻給世界環(huán)境...
    茶點故事閱讀 39,324評論 3 307
  • 文/蒙蒙 一成箫、第九天 我趴在偏房一處隱蔽的房頂上張望伟众。 院中可真熱鬧召廷,春花似錦竞慢、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,315評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽檬洞。三九已至沟饥,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間广料,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,539評論 1 262
  • 我被黑心中介騙來泰國打工韧衣, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留汹族,地道東北人。 一個月前我還...
    沈念sama閱讀 45,578評論 2 355
  • 正文 我出身青樓夸政,卻偏偏與公主長得像,于是被迫代替她去往敵國和親匀归。 傳聞我的和親對象是個殘疾皇子穆端,可洞房花燭夜當晚...
    茶點故事閱讀 42,877評論 2 345

推薦閱讀更多精彩內(nèi)容