spring boot2.x 使用swagger2

spring boot2.x 使用swagger2

1.添加依赖

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

2.启动EnableSwagger2

package com.lzsz.wemall.config;

import io.swagger.annotations.ApiOperation;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("wemall Manage Swagger RESTful APIs")
                .description("微商城 Swagger API 服务")
                .termsOfServiceUrl("http://swagger.io/")
                .contact(new Contact("wemall", "127.0.0.1", "wanghaibo@163.com.cn"))
                .version("1.0")
                .build();
    }

}

3.使用Api来编写Controller

package com.lzsz.wemall.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzsz.wemall.common.PageResult;
import com.lzsz.wemall.entity.WxSharePage;
import com.lzsz.wemall.mapper.WxSharePageMapper;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wanghaibo
 * @version V1.0
 * @desc
 * @date 2018/8/23 11:20
 */
@Api(value = "推荐搭配",description = "推荐搭配")
@RestController
@RequestMapping("wxSharePage")
public class WxSharePageController {
    private static final Logger logger = LoggerFactory.getLogger(WxSharePageController.class);
    private final WxSharePageMapper wxSharePageMapper;


    @Autowired
    public WxSharePageController(WxSharePageMapper wxSharePageMapper) {
        this.wxSharePageMapper = wxSharePageMapper;
    }

    @ApiOperation(value = "分享过的商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name ="employeeId",value = "员工编号",required = true,dataType = "String"),
            @ApiImplicitParam(name ="region",value = "区域",required = true,dataType = "String"),
            @ApiImplicitParam(name ="sortBy",value = "排序", dataType = "String"),
            @ApiImplicitParam(name ="pageSize",value = "页码",dataType = "Integer"),
            @ApiImplicitParam(name ="page",value = "分页数",dataType = "Integer")
    })
    @GetMapping("/getList")
    @ResponseBody
    public PageResult getList(
            // @ApiParam(name ="employeeId",value = "员工编号") 
            @RequestParam("employeeId") String employeeId,
            // @ApiParam(name ="region",value = "区域") 
            @RequestParam("region") String region,
            // @ApiParam(name ="sortBy",value = "排序") 
            @RequestParam(value = "sortBy", defaultValue = "create_time desc", required = false) String sortBy,
            // @ApiParam(name ="pageSize",value = "页码") 
            @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
            // @ApiParam(name ="page",value = "分页数") 
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page
    ) {
        logger.info("op=start_getList, employeeId={}, region={}, sortBy={}, pageSize={}, page={}", employeeId, region, sortBy, pageSize, page);

        Map<String, Object> params = new HashMap<>();
        params.put("createByOpenid", employeeId);
        params.put("region", region);

        PageHelper.startPage(page, pageSize, sortBy);

        PageResult<WxSharePage> result = new PageResult<>();
        List<WxSharePage> list = wxSharePageMapper.getList(params);
        result.setList(list);
        PageInfo<WxSharePage> pageInfo = new PageInfo<>(list);
        result.setPage(pageInfo.getPageNum());
        result.setSize(pageInfo.getPageSize());

        return result;
    }
}
package com.lzsz.wemall.entity;

import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

public class WxSharePage implements Serializable {
    private static final long serialVersionUID = 3184283145156339652L;

    // 主键ID
    // 使用该注解描述属性信息,当hidden=true时,该属性不会在api中显示
    @ApiModelProperty(value="主键", hidden=false, notes="主键,隐藏", required=true, dataType="Long")
    private Long id;
    // 页面地址
    @ApiModelProperty(value="URL链接地址")
    private String pageUrl;
   ……省略getter,setter方法……
}

常用swaggerui注解:

  • @Api() 用于类;

​ 表示标识这个类是swagger的资源

  • @ApiOperation() 用于方法;

​ 表示一个http请求的操作

  • @ApiParam() 用于方法,参数,字段说明;
    ​ 表示对参数的添加元数据(说明或是否必填等)
  • @ApiModel() 用于类

​ 表示对类进行说明,用于参数用实体类接收

  • @ApiModelProperty() 用于方法,字段

​ 表示对model属性的说明或者数据操作更改

  • @ApiIgnore() 用于类,方法,方法参数

​ 表示这个方法或者类被忽略

  • @ApiImplicitParam() 用于方法

​ 表示单独的请求参数

  • @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

swagger2 注解整体说明

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"

@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

4.spring boot 2.x 本地访问404

package com.lzsz.wemall.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
        // 解决 SWAGGER 404报错
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {

    }

}

解决第一次刷新报错的问题 java.lang.NumberFormatException: For input string: ""

@GetMapping("/{id}")
    @ResponseBody
    @ApiOperation(value = "获取分享详情", notes = "通过主键ID获取分享详情", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "主键ID", dataType = "Long", paramType = "path")
    public String get(
            // @ApiParam(name ="id",value = "主键ID")
            @PathVariable("id") Long id) {

        log.info("SAMPLE-GET method called");
        log.info("op=start_getDetail, id={}", id);

        return "SAMPLE";
    }

在pom.xml里面
去掉了以前的swagger版本(1.5.20),并添加了新的

详情

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
	<exclusions>
		<exclusion>
			<groupId>io.swagger</groupId>
			<artifactId>swagger-annotations</artifactId>
		</exclusion>
		<exclusion>
			<groupId>io.swagger</groupId>
			<artifactId>swagger-models</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>
<dependency>
	<groupId>io.swagger</groupId>
	<artifactId>swagger-annotations</artifactId>
	<version>1.5.21</version>
</dependency>
<dependency>
	<groupId>io.swagger</groupId>
	<artifactId>swagger-models</artifactId>
	<version>1.5.21</version>
</dependency>
// 使用下面的方法更有效 给需要的地方添加 example = "123"
@Data
@ApiModel(description = "订单查询请求数据")
public class OrderQueryReq implements Serializable {
    @ApiModelProperty(value = "订单ID",example = "123")
    private Integer id;
}

@ApiOperation(value = "获取工作日志详情", notes = "通过ID获取工作日志详情")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long", paramType = "path", example = "1")
    @GetMapping("/{id}")
    public ResponseEntity<Response> get(@PathVariable("id") Long id){}

访问的参数是List 的时候

使用
allowMultiple=true,————表示是数组格式的参数
dataType = “SortIdDto”————表示数组中参数的类型

@ApiOperation(value = "批量修改导购微商城文章排序", notes = "批量修改导购微商城文章排序")
@ApiImplicitParam(name = "sortLists", value = "List实体", required = true, dataType = "SortIdDto",allowMultiple = true)
@ResponseBody
@PutMapping("/sort")
public ResultResponse updateSort(@RequestBody List<SortIdDto> sortLists) {

    wxShareArticleMapper.updateSort(sortLists);

    return ResultResponse.ofStatus(SUCCESS);
}

原文:https://www.itsocoo.com/2018/05/12/swagger2的使用/

向楼主安利一款API生成的工具,smart-doc

1 个赞