Spring boot + Swagger 入門搭建

導語:

Spring-Boot Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力于在蓬勃發展的快速應用開發領域(rapid application development)成為領導者。

特點

  • 創建獨立的Spring應用程序
  • 嵌入的Tomcat,無需部署WAR文件
  • 簡化Maven配置
  • 自動配置Spring
  • 提供生產就緒型功能,如指標,健康檢查和外部配置
  • 絕對沒有代碼生成和對XML沒有要求配置

創建Spring-boot項目

  1. 使用IDEA 選擇Spring Initalizr -->Next


  2. 可以什么都不選,直接下一步


  3. 勾選web


  4. 完成創建


POM配置

<!--boot start-->
<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>
<!--boot end-->

啟動 Spring-Boot 項目

  • 創建 DomeController.java

      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      
      @SpringBootApplication
      public class DomeController {
      
         public static void main(String[] args) {
            SpringApplication.run(DomeController.class, args);
         }
      } 
    
  • 創建方法 helloSpringBoot

  •    @RequestMapping(value = "/hello")
      public String helloSpringBoot(){
          return "Hello SpringBoot";
      }
    
  • 在剛剛創建的項目中找到 DomeApplication.java 并啟動它

  • 瀏覽器請求localhost:8080/dome/hello

Swagger

Swagger 是一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件。本文簡單介紹了在項目中集成swagger的方法和一些常見問題。Swagger 是一個規范和完整的框架,用于生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。

學習之前我們需要做一點準備
  1. 創建User類
  2. Swagger2 服務類
  3. 創建UserController.java
  4. 啟動SpringBoot
  5. 查看Swagger UI頁面

引入POM

    <!--swagger start-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
    </dependency>

    <!--swagger end-->

創建User類

public class User implements Serializable{  
    private String name;
    private Integer age;
    private long id;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
} 

Swagger2 服務類

swagger-服務關鍵代碼:必須和boot 服務啟動類同一目錄
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sanqiange"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構建RESTful APIs")
                .description("更多Spring Boot相關文章請關注:http://blog.didispace.com/")
                
                .termsOfServiceUrl("http://blog.didispace.com/")
                .contact("dd")
                .version("1.0")
                .build();
    }

}

創建UserController.java

import com.sanqian.entity.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
@RequestMapping(value = "/users")// 通過這里配置使下面的映射都在/users下,可去除
public class UserController {
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    /**
     * @return
     * @ApiOperation 方法添加注釋
     * @RequestMapping 指定方法路徑
     */
    @ApiOperation(value = "獲取用戶列表",
            notes = "注釋",
            httpMethod = "GET",
            nickname = "getUserList",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = {""}, method = RequestMethod.GET)
    public List<User> getUserList() {
        List<User> r = new ArrayList<User>(users.values());
        return r;
    }

    /**
     * @param user
     * @return
     * @ApiImplicitParam 注解來給參數增加說明
     */
    @ApiOperation(value = "創建用戶", notes = "根據User對象創建用戶", httpMethod = "POST")
    @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public String postUser(@RequestBody User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value = "獲取用戶詳細信息", notes = "根據url的id來獲取用戶詳細信息", httpMethod = "GET")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用戶ID", required = true, dataType = "Long")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @ApiOperation(value = "更新用戶詳細信息", notes = "根據url的id來指定更新對象,并根據傳過來的user信息來更新用戶詳細信息", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "用戶ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @RequestBody User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @ApiOperation(value = "刪除用戶", notes = "根據url的id來指定刪除對象", httpMethod = "DELETE")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用戶ID", required = true, dataType = "Long")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }
}

啟動SpringBoot

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

@SpringBootApplication
public class CenterApplication {

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

查看Swagger UI頁面

地址欄輸入localhost:8080/swagger-ui.html#/

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

推薦閱讀更多精彩內容