成人无码视频,亚洲精品久久久久av无码,午夜精品久久久久久毛片,亚洲 中文字幕 日韩 无码

資訊專欄INFORMATION COLUMN

Java | Spring Boot Swagger2 集成REST ful API 生成接口文檔

joyvw / 3291人閱讀

摘要:集成生成接口文檔原文簡介由于的特性,用來開發(fā)變得非常容易,并且結(jié)合來自動生成文檔變得方便快捷。使用生成,我們可以得到交互式文檔。聽過與的結(jié)合,生成更加完備的文檔。接下來將基于與搭建完整的文檔系統(tǒng)。

Spring Boot Swagger2 集成REST ful API 生成接口文檔

原文

簡介

由于Spring Boot 的特性,用來開發(fā) REST ful 變得非常容易,并且結(jié)合 Swagger 來自動生成 REST ful API 文檔變得方便快捷。

Swagger 是一個(gè)簡單但功能強(qiáng)大的API表達(dá)工具。幾乎所有的語言都可以找到與之對應(yīng)的Swagger 版本。使用Swagger生成API,我們可以得到交互式文檔。聽過Spring Boot 與Swagger 的結(jié)合,生成更加完備的REST ful API 文檔。通過在源碼中添加部分內(nèi)容,系統(tǒng)生成文檔,大大提高工作效率,不用再花費(fèi)大量時(shí)間來創(chuàng)建文檔,同時(shí)由于同時(shí)是通過代碼開生成文檔,大大降低了維護(hù)成本
Swagger 不僅可以組織生成強(qiáng)大的 REST ful 文檔,同時(shí)也提供了完備的測試功能,可以直接在文檔頁面測試接口功能。

接下來將基于 Spring Boot 與Swagger 2 搭建完整的API 文檔系統(tǒng)。先來提前目睹下Swagger 生成的文檔樣式

實(shí)踐 創(chuàng)建Spring Boot 工程

可以參考前文Spring Boot 初體驗(yàn)

在POM 文件中添加 Swagger2 包引用
    
        io.springfox
        springfox-swagger2
        2.7.0
    
    
        io.springfox
        springfox-swagger-ui
        2.7.0
    
    
    //導(dǎo)入測試需要的庫 
            
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            com.h2database
            h2
            1.4.196
            runtime
        
    

本實(shí)例采用的是基于內(nèi)存數(shù)據(jù)庫H2 的JPA 形式

創(chuàng)建配置類

通過以上方式只能導(dǎo)入 Swagger2 需要的jar包,但當(dāng)前并不能運(yùn)行(雖然Spring boot 支持自動化配置)

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api(){
        return  new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors.basePackage("com.springboot.demo"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構(gòu)建RESTful APIs")
                .description("spring boot , swagger2")
                .termsOfServiceUrl("http:github.com/zhuamaodeyu")
                .contact("抓?的?")
                .version("1.0")
                .build();
    }
}

說明:

@Configuration: 此注解是告訴 Spring Boot 這是一個(gè)配置類,需要在項(xiàng)目啟動時(shí)加載該類

@EnableSwagger2: Swagger2 是通過此注解來啟動的

通過 api方法創(chuàng)建 Docket 對象,其中主要注意 basePackage配置以及私有方法 apiInfo方法創(chuàng)建的基本信息
通過指定掃描包來配置,以上配置 Swagger 會掃描整個(gè)項(xiàng)目工程

創(chuàng)建實(shí)體和respository
@Entity
@Table(name="user")
public class User implements Serializable {
//    @ApiModelProperty(notes = "id")
    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)
    private  String id;
    @ApiModelProperty(notes = "uuid")
    private UUID uuid;
    @ApiModelProperty(notes = "用戶名稱")
    private  String name;
    private  String password;
    @ApiModelProperty(notes = "用戶地址")
    private  String address;
    @ApiModelProperty(notes = "年齡")
    private  int age;
    @ApiModelProperty(notes = "郵箱地址")
    private  String email;
    @ApiModelProperty(notes = "描述")
    private  String desc;
    
    // getter/ setter 方法

}

@Repository
public interface UserRepository extends  CrudRepository {

}

測試controller
@RestController
@Api(value = "product 商品操作API")
@RequestMapping("/product")
public class IndexController {

    /**
     * 1. 獲取列表
     * 2. 顯示單個(gè)的信息
     * 3. 添加
     * 4. 更新
     * 5. 刪除
     */

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/")
    @ApiOperation(value = "首頁",notes = "測試代碼")
    public  String index()
    {
        return  "index";
    }



    @GetMapping("/list")
    @ApiOperation(value = "獲取全部數(shù)據(jù)列表", notes = "獲取數(shù)據(jù)列表")
    public Iterable list(Model model)
    {
        return  userRepository.findAll();
    }

    @GetMapping("/get_user_message")
    @ApiOperation(value = "獲取用戶詳情信息")
    @ApiImplicitParam(name = "userId",value = "用戶ID",defaultValue = "",required = true,dataType = "String")
    public User getUserMessage(String userId)
    {
        return  userRepository.findOne(userId);
    }


    @PostMapping("/save")
    @ApiOperation(value = "保存用戶數(shù)據(jù)")
    @ApiImplicitParam(name = "user", value = "用戶對象",required = true, dataTypeClass = User.class)
    public String save(@RequestBody User user)
    {
        if (user == null)
        {
            return  "false";
        }

        userRepository.save(user);
        return  "true";
    }

    @PutMapping("/update/{userId}")
    @ApiOperation(value = "更新用戶數(shù)據(jù)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用戶的ID", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "user", value = "用戶對象", required = true, dataTypeClass = User.class)
    })

    public ResponseEntity updateUserMessage(@PathVariable String userId, @RequestBody User user)
    {
        User user1 = userRepository.findOne(userId);
        user1.setAddress(user.getAddress());


        userRepository.save(user1);
        return  new ResponseEntity("更新數(shù)據(jù)成功", HttpStatus.OK);
    }

    @DeleteMapping("/delete/{userId}")
    @ApiOperation(value = "根據(jù)用戶ID 刪除用戶數(shù)據(jù)")
    @ApiImplicitParam(name = "刪除用戶數(shù)據(jù)",value = "",required = true, dataType = "String")
    public  ResponseEntity deleteUser(@PathVariable String userId)
    {
        userRepository.delete(userId);
        return new ResponseEntity("刪除用戶數(shù)據(jù)", HttpStatus.OK);
    }
}
測試

實(shí)現(xiàn)以上代碼,啟動項(xiàng)目 直接訪問http://localhost:8080/swagger-ui.html
就能看到Swagger2 所生成的文檔??梢圆僮髅總€(gè)請求,其下面是具體的描述和文檔內(nèi)容

接口調(diào)試

Swagger 集成測試
前文提到 Swagger 也提供了 接口調(diào)試功能, 可以直接根據(jù)接口要求在圖中標(biāo)記處填寫接口參數(shù)

Postman 測試
通過以上方式可以得到接口文檔,其包含了具體的內(nèi)容,有了這些內(nèi)容,就可以通過Postman 等專業(yè)的接口測試工具來進(jìn)行接口的測試

Swagger2 常用配置詳解

@Api

@Api(value="onlinestore", description="當(dāng)前控制器中的API 的描述信息")

@ApiOperation

此注解是對當(dāng)前 API 接口的描述,主要是名稱,詳細(xì)描述,返回值類型等信息

@ApiOperation(value = "首頁",notes = "測試代碼", tags = {"測試服務(wù)是否正常"}, response = String.class)

value : API 的名稱

notes : API 詳細(xì)描述信息

response : 返回值類型

tags : 默認(rèn)的是以 類名為 標(biāo)簽的,此處可以自定義標(biāo)簽

@ApiResponses

@ApiResponse

此注解是對API 返回的結(jié)果進(jìn)行描述

   @ApiResponses(value = {
        @ApiResponse(code = 200, message = "Successfully"),
        @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
        @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
        @ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
}
)

@ApiImplicitParams

@ApiImplicitParam

這兩個(gè)注解是對API 請求參數(shù)的描述

@ApiImplicitParams({
        @ApiImplicitParam(name = "userId", value = "用戶的ID", required = true, dataTypeClass = String.class),
        @ApiImplicitParam(name = "user", value = "用戶對象", required = true, dataTypeClass = User.class)
})

@ApiModelProperty
實(shí)體類屬性添加描述信息,在接口文檔中可針對類屬性具體含義進(jìn)行查看

@GeneratedValue(strategy = GenerationType.AUTO)
private  String id;
@ApiModelProperty(notes = "uuid")
private UUID uuid;
@ApiModelProperty(notes = "用戶名稱")
private  String name;
private  String password;
@ApiModelProperty(notes = "用戶地址")
private  String address;
@ApiModelProperty(notes = "年齡")
private  int age;
@ApiModelProperty(notes = "郵箱地址")
private  String email;
@ApiModelProperty(notes = "描述")
private  String desc;

通過以上配置,可以文檔中進(jìn)行查看

擴(kuò)展知識 Mock 系統(tǒng)

在現(xiàn)如今的開發(fā)中,一個(gè)由于項(xiàng)目需求緊,開發(fā)周期短,通常涉及到后端以及前端協(xié)同工作;一個(gè)由于現(xiàn)在大多采用的是前后端分離的開發(fā)形式,前后端交互只是通過 REST ful 接口形式來實(shí)現(xiàn)的,前后端各自分工工作,所以就存在一個(gè)現(xiàn)象就是前端做的快,后端無法及時(shí)的給出接口實(shí)現(xiàn)并且開發(fā)階段沒有數(shù)據(jù)支撐而造成前端必須等待后端。

現(xiàn)在可以通過先定義接口文檔,生成 Mock 數(shù)據(jù)的形式來進(jìn)行前后端分離開發(fā)。前端通過調(diào)用定義的 Mock 數(shù)據(jù)來進(jìn)行前端調(diào)試和開發(fā)。不需要等待后端的數(shù)據(jù)

接下來將通過集成 easy-Mock 系統(tǒng)來實(shí)現(xiàn)協(xié)同開發(fā)

easy Mock

easy-mock 是大搜車公司開源的一套 mock 工具,是一個(gè)可視化,并且能快速生成 模擬數(shù)據(jù) 的持久化服務(wù). 下面將 easy-mock 與 Swagger 結(jié)合進(jìn)行協(xié)同工作

搭建easy-mock

下載源碼
easy-mock是一套開源系統(tǒng),其托管在 github 上,可以通過一下方式獲取源碼
git clone https://github.com/easy-mock/easy-mock.git

修改配置
easy-mock 是使用MongoDB數(shù)據(jù)的,所以需要配置數(shù)據(jù)庫
進(jìn)入 config文件夾,修改 default.json文件

{
      "port": 7300,
      "pageSize": 30,
      "routerPrefix": {
        "mock": "/mock",
        "api": "/api"
      },
      "db": "mongodb://192.168.99.100:32773/easy-mock_",
      "unsplashClientId": "",

修改 db 添加一個(gè)可以用的 數(shù)據(jù)庫

啟動
npm run dev
默認(rèn)的監(jiān)聽 7300 端口,可以通過localhost:7300訪問系統(tǒng)

導(dǎo)入 Swagger
進(jìn)入系統(tǒng)創(chuàng)建項(xiàng)目并根據(jù)以下方式導(dǎo)入 Swagger

獲取 Swagger 地址

easy-mock創(chuàng)建項(xiàng)目

通過

參考

Easy-Mock

SPRING BOOT RESTFUL API DOCUMENTATION WITH SWAGGER 2

Setting Up Swagger 2 with a Spring REST API

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://m.hztianpu.com/yun/70753.html

相關(guān)文章

  • 《 Kotlin + Spring Boot : 下一代 Java 服務(wù)端開發(fā) 》

    摘要:下一代服務(wù)端開發(fā)下一代服務(wù)端開發(fā)第部門快速開始第章快速開始環(huán)境準(zhǔn)備,,快速上手實(shí)現(xiàn)一個(gè)第章企業(yè)級服務(wù)開發(fā)從到語言的缺點(diǎn)發(fā)展歷程的缺點(diǎn)為什么是產(chǎn)生的背景解決了哪些問題為什么是的發(fā)展歷程容器的配置地獄是什么從到下一代企業(yè)級服務(wù)開發(fā)在移動開發(fā)領(lǐng)域 《 Kotlin + Spring Boot : 下一代 Java 服務(wù)端開發(fā) 》 Kotlin + Spring Boot : 下一代 Java...

    springDevBird 評論0 收藏0
  • SpringBoot 實(shí)戰(zhàn) (五) | 集成 Swagger2 構(gòu)建強(qiáng)大的 RESTful API

    摘要:今天給你們帶來集成的教程。接口返回結(jié)果不明確。這些痛點(diǎn)在前后端分離的大型項(xiàng)目上顯得尤為煩躁。接口返回結(jié)果非常明確,包括數(shù)據(jù)類型,狀態(tài)碼,錯誤信息等。生成后的文件依賴如下這里使用的是的版本。另外,關(guān)注之后在發(fā)送可領(lǐng)取免費(fèi)學(xué)習(xí)資料。 微信公眾號:一個(gè)優(yōu)秀的廢人如有問題或建議,請后臺留言,我會盡力解決你的問題。 前言 快過年了,不知道你們啥時(shí)候放年假,忙不忙。反正我是挺閑的,所以有時(shí)間寫 b...

    Rindia 評論0 收藏0
  • SpringBoot 2.X Kotlin與Swagger2生成API文檔

    摘要:再通過函數(shù)創(chuàng)建的之后,用來創(chuàng)建該的基本信息這些基本信息會展現(xiàn)在文檔頁面中。函數(shù)返回一個(gè)實(shí)例用來控制哪些接口暴露給來展現(xiàn),本例采用指定掃描的包路徑來定義,會掃描該包下所有定義的,并產(chǎn)生文檔內(nèi)容除了被指定的請求。 showImg(http://download.qfeoo.com/kotlin_springboot_logo.png); 這里有個(gè)地方需要注意,在測試WebFlux集成Swa...

    cyqian 評論0 收藏0

發(fā)表評論

0條評論

閱讀需要支付1元查看
<