swagger 修改dto注解_Spring Boot 使用 swagger 实现Rest Api 文档化

Swagger 是一个简单、功能强大、非常流行的API 表达工具。基于Swagger 生成API,可以得到交互式文档、自动生成代码的SDK,以及API 的发现方式。

Swagger 允许用户在一个html5 web 页面中,对API 进行文档化和交互。

优点:

  • 功能丰富:支持多种注解,自动生成接口文档界面,支持在界面测试API接口功能;
  • 及时更新:开发过程中花一点写注释的时间,就可以及时的更新API文档,省心省力;
  • 整合简单:通过添加pom依赖和简单配置,内嵌于应用中就可同时发布API接口文档界面,不需要部署独立服务。

如下是自动生成的API 文档界面:

0caacf5d09ad1c73533fd187d5ebb725.png

实现 Swagger 文档

1. 添加依赖

主要是 添加 swagger2 核心包 以及 swagger-ui界面包的依赖。

io.springfox

springfox-swagger2

2.7.0

io.springfox

springfox-swagger-ui

2.7.0

2. 编写Swagger的配置类

package com.rickie;

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.rickie.rest"))

.paths(PathSelectors.any())

.build();

}

private ApiInfo apiInfo() {

return new ApiInfoBuilder()

.title("Swagger构建RESTful API")

.description("")

.termsOfServiceUrl("")

.version("1.0")

.build();

}

}

3. 在controller 中编写自己的api 文档,主要是参数和接口的描述

如下是ProductController.java 的示例代码。

package com.rickie.rest;

import com.rickie.dto.Product;

import io.swagger.annotations.ApiImplicitParam;

import io.swagger.annotations.ApiOperation;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

import java.util.List;

@RestController

@RequestMapping(value="/products") // 通过这里配置使下面的映射都在/products下

public class ProductController {

private List productList;

//初始化

public ProductController(){

productList = new ArrayList();

for (int i = 0; i < 10; i++) {

Product product =new Product();

product.setId(i);

product.setCount(i+10);

product.setName("watch"+i);

product.setDesc("watch desc"+i);

productList.add(product);

}

}

@ApiOperation(value="获取产品列表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值