SpringBoot+Swagger生成接口文档页面

1.加入maven依赖

<dependencies>
    <dependency>
        <groupId>io.springfoxgroupId>
        <artifactId>springfox-swagger2artifactId>
        <version>2.9.2version>
    dependency>
    <dependency>
        <groupId>io.springfoxgroupId>
        <artifactId>springfox-swagger-uiartifactId>
        <version>2.9.2version>
    dependency>
dependencies>

2.新建一个Swagger配置类

package com.example.demo;

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 SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controllers"))//这里要写扫描的controller包名
                .paths(PathSelectors.any()).build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("使用Swagger2")//文档网页的标题
                .version("1.0").build();
    }
}

3.建一个controller加上swagger的各种注解

package com.example.demo.controllers;

import com.example.demo.model.Person;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = "HelloWorldController", description = "HelloWorldController | 用HelloWorldController来测试swagger")
public class HelloWorldController {


    @ApiOperation(value="demo方法", notes="这是demo方法")
    @RequestMapping(value = "/demo",method = {RequestMethod.POST})
    public String demo()
    {
        return "Hello  World! Spring Boot!";
    }

    @ApiOperation(value="test方法", notes="这是test方法")
    @ApiImplicitParam(name = "person", value = "Person实体", required = true, dataType = "Person")
    @RequestMapping(value = "/test",method = {RequestMethod.GET})
    public Person test()
    {
        return new Person("张三",15,"男");
    }
}

到此为止,目录结构为:
SpringBoot+Swagger生成接口文档页面_第1张图片

注意Person类只是我建的一个无关紧要的实体类

4.启动项目

好了,现在我们在主方法启动项目,然后访问:http://localhost:8080/swagger-ui.html

界面如下:
SpringBoot+Swagger生成接口文档页面_第2张图片

点击各个选项卡即可看到接口文档详细信息:
SpringBoot+Swagger生成接口文档页面_第3张图片

你可能感兴趣的:(JavaWeb,spring)