SpringBoot集成Swagger2构建RESTful API文档

[Swagger2提供以下能力]:
1.随项目自动生成强大RESTful API文档,减少工作量
2.API文档与代码整合在一起,便于同步更新API说明
3.页面测试功能来调试每个RESTful API

添加依赖

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

SwaggerConfig.java内容如下:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.boot"))// 指定扫描包下面的注解
                .paths(PathSelectors.any())
                .build();
    }
      // 创建api的基本信息
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("集成Swagger2构建RESTful APIs")
                .description("集成Swagger2构建RESTful APIs")
                .termsOfServiceUrl("https://www.baidu.com")
                .contact("zhangsan")
                .version("1.0.0")
                .build();
    }
}

创建Controller: SwaggerController.java

@RestController
@RequestMapping(value="/swagger")
public class SwaggerController {
    @ApiOperation(value="获取用户信息", notes="根据id来获取用户详细信息")
    @ApiImplicitParam(name="id", value="用户ID", required=true, dataType="String")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public Map<String,String> getInfo(@PathVariable String id) {
      Map<String ,String> map = new HashMap<String, String>();
      map.put("name", "张三");
      map.put("age", "34");
        return map;
    }
}

启动Spring boot,访问Swagger UI界面:http://localhost:8081/swagger-ui.html

猜你喜欢

转载自blog.csdn.net/qyj19920704/article/details/80638388