Spring Boot起步:a RESTful Web Service

本文將講述如何通過使用Spring Boot 快速起步搭建web服務。

最終實現:

位于如下位置的HTTP服務,

http://localhost:8080/greeting

返回如下JSON數據:

{"id":1,"content":"Hello, World!"}

或帶有name參數:

http://localhost:8080/greeting?name=User
//Response
{"id":1,"content":"Hello, User!"}

前提:

  • IDEA
  • JDK 1.8
  • Maven 3.0+

創建工程:

  1. IDEA選擇Create New Project。
    創建工程-1.png
  2. 確定Java版本,選擇Maven工程。
    創建工程-2.png
  3. 自己起一個GroupIDArtifactId吧。IDEA會根據ArtifactId自動生成工程名。下面的Version會體現在pom.xml中。
    創建工程-3.png
  4. 最后一步可以手動修改工程名稱以及存儲位置。點擊Finish。
    創建工程-4.png
  5. 修改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.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework</groupId>
    <artifactId>gs-rest-service</artifactId>
    <version>0.1.0</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>
  1. 此時IDEA會出現如下提示,選擇Enable Auto-Import。(或者在工程根目錄命令行輸入mvn compile
    創建工程-5.png

書寫代碼

創建Model

我們將Greeting的主要邏輯實現在Greeting中:
src/main/java/hello/Greeting.java

package hello;

public class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

創建Controller

在Spring中,請求由controller來處理。Spring通過@RestController
注解輕松識別controller。
我們實現的GreetingController處理對greeting的請求,并返回Greeting類的新實例。
src/main/java/hello/GreetingController.java

package hello;

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

其中:

  1. @RequestMapping注解將發送到/greeting的http請求映射到greeting()方法。
  2. @RequestParam將請求中name參數的值映射到greeting()方法的name參數,并提供了defaultValue.

創建應用入口

按照傳統方式,我們已經可以將上述內容打包為war文件,并上傳至tomcat運行。但Spring Boot可以幫助我們快速創建包含內嵌tomcat的獨立應用。
src/main/java/hello/Application.java

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

其中:

  1. @SpringBootApplication注解用以標注SpringBoot應用。
  2. SpringApplication.run()方法啟動應用。

運行程序

此時程序已經可以運行了。如果用IDEA,直接點擊run;如果不用,在命令行輸入mvn spring-boot:run

Paste_Image.png

運行結果

Result-1.png
Result-2.png

可以注意到id從1變化為2,可以說明即使有多個請求,GreetingController也只有一個實例,counter根據每次請求增長。

總結

以上,我們已經成功使用Spring Boot建立了一個Restful web service

參考:http://spring.io/guides/gs/rest-service/

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容