SpringBoot 集成Swagger

SpringBoot 集成Swagger

1.maven 配置

       <!--springfox-swagger需要的最小依赖 start-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.5.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.5.0</version>
        </dependency>

2. SwaggerConfig

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig  {

    /**
     如果项目配置tomcat访问路径,例如qdp-wain-web这样,需要配置下面的pathProvider方法,
     未配置访问路径,则忽略pathProvider方法和HOST配置
     **/
    @Value("${spring.swagger.host}")
    private String Host;

    @Bean
    public Docket swaggerSpringMvcPlugin(ServletContext servletContext) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//生成文档的api对象定义
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.jimingqiang.study"))//扫描生成文档的包路径
                //.paths(PathSelectors.ant("/*Api/*"))//生成文档的类访问路径,就是controller类里@RequestMapping("orderApi")
                .paths(PathSelectors.any())
                .build();
                //.host(Host);//配置swagger前缀
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("JMQ-WEB构建restful接口api")//文档标题
                .description("此API提供接口调用")//文档说明
                .version("2.0").build();//版本号
    }



}

  • SwaggerConfig必须与启动类同级,否则后台报错:

    No mapping found for HTTP request with URI [/swagger-ui.html] in DispatcherServlet with name 'dispatcherServlet'
    
    1539054671(1).jpg

3. swagger-ui.html的映射

代码如下:

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

1539055241(1).jpg
  • 后台错误:

    No mapping found for HTTP request with URI [/swagger-ui.html] in DispatcherServlet with name 'dispatcherServlet'
    

4.注解

@Api:

作用在类上,用来标注该类具体实现内容。表示标识这个类是swagger的资源 。
参数:

  1. tags:可以使用tags()允许您为操作设置多个标签的属性,而不是使用该属性。
  2. description:可描述描述该类作用。
@RestController
@RequestMapping("/swaggerApi")
@Api(value = "SwaggerValue", tags={"SwaggerController"},description = "swagger应用",  produces = MediaType.APPLICATION_JSON_VALUE)
public class SwaggerController {
Api.jpg

@ApiOperation

用于方法;表示一个http请求的操作
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)

    @RequestMapping(value="/test", method= RequestMethod.GET)
    @ApiOperation(value="获取swagger信息",httpMethod = "GET",notes="注意问题点",produces = MediaType.APPLICATION_JSON_VALUE)
    public String swaggerTest(@ApiParam(name="id",value="用户id",required=true) Long id){

        return "swagger"+id;

    }
ApiOperation.jpg

@ApiParam

用于方法,参数,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填

 public String swaggerTest(@ApiParam(name="id",value="用户id",required=true) Long id){
        return "swagger"+id;
    }

ApiParam.jpg

@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
都可省略
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏

    @RequestMapping(value="/apiModeltest", method= RequestMethod.GET)
    @ApiOperation(value="获取ApiModel信息",httpMethod = "GET",notes="ApiModel注意问题点",produces = MediaType.APPLICATION_JSON_VALUE)
    public String swaggerTest1(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user ){

        return user.toString();

    }
@Data
@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable {
    @ApiModelProperty(value="用户名",name="username",required = true,example="xingguo")
    private String name;

    @ApiModelProperty(value="用户年龄",name="age",required = true,example="24")
    private int age;

}
ApiModel.jpg

@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上
比较简单, 这里不做举例

@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上
​ 比较简单, 这里不做举例

@ApiImplicitParam() 用于方法 表示单独的请求参数

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

  • name–参数名

  • value–参数说明

  • dataType–参数的数据类型

  • example–举例说明

  • required-参数是否必填

  • paramType–查询参数类型,这里有几种形式

paramType.jpg

注意:当我发POST请求的时候,当时接受的整个参数,不论我用body还是query,后台都会报Body Missing错误。这个参数和SpringMvc中的@RequestBody冲突,索性我就去掉了paramType,对接口测试并没有影响。

    @RequestMapping(value="/apiImplicitParamsTest", method= RequestMethod.GET)
    @ApiOperation(value="获取apiImplicitParams信息",httpMethod = "GET",notes="apiImplicitParams注意问题点",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名字", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "用户id", required = false, dataType = "long", paramType = "query")})
    public String apiImplicitParamsTest(Long id,String name ){

        return name;

    }
    
ApiImplicitParam.jpg

ApiImplicitParam 与 ApiParam 的区别
​ ApiImplicitParam: This is the only way to define parameters when using Servlets or other non-JAX-RS environments.

  • 对Servlets或者非 JAX-RS的环境,只能使用 ApiImplicitParam。
  • 在使用上,ApiImplicitParam比ApiParam具有更少的代码侵入性,只要写在方法上就可以了,但是需要提供具体的属性才能配合swagger ui解析使用。
  • ApiParam只需要较少的属性,与swagger ui配合更好。

彩蛋

微服务学习二:springboot与swagger2的集成

SpringBoot集成Swagger2中遇到的问题

Swagger-Core Annotations

swagger2的常用注解,传递参数的注意使用方法](https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#api)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。