Spring集成Swagger,Java自动生成Api文档

时间:2021-11-14 10:43:17

博主很懒...

Swagger官网:http://swagger.io

GitHub地址:https://github.com/swagger-api

官方注解文档:http://docs.swagger.io/swagger-core/apidocs/index.html

Swagger-UI地址:https://github.com/swagger-api/swagger-ui

swagger最终效果图

Spring集成Swagger,Java自动生成Api文档

好,开始说Spring怎么配置Swagger了

1.pom.xml引入需要的jar包

<!-- 构建Restful API 我这版本是2.6.1 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger2.version}</version>
</dependency>

2.扫描你的Swagger2config.java所在的包

<!-- url是你需要扫描swagger的包路径 -->
<context:component-scan base-package="com.nickwilde.microtrain.common.config.swagger"/>

3.Swagger2config.java[类名自定义]

package com.nickwilde.microtrain.common.config.swagger2;

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; /**
* @author NickWilde
* @version 2018/1/18 10:23
* @description: Swagger2Config
* TODO 用一句话描述
*/
@Configuration
@EnableSwagger2
public class Swagger2Config{
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).forCodeGeneration(true)
.select()
.apis(RequestHandlerSelectors.any())
//过滤生成链接
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
} //api接口作者相关信息
private ApiInfo apiInfo() {
Contact contact = new Contact("NickWilde", "", "1064698801@qq.com");
ApiInfo apiInfo = new ApiInfoBuilder()
.license("Apache License Version 2.0")
.title("Unexpectedly系统")
.description("接口文档")
.contact(contact)
.version("1.0")
.build();
return apiInfo;
}
}

4.给你的controller加上额外注解(不加也是有的)

@ApiOperation(value="根据User对象创建用户", notes="根据User对象创建用户",httpMethod = "POST") //httpMehtod如果不定义,那么swagger会有把该接口的所有请求方法都一一列举出来
@ApiImplicitParam(name = "data", value = "data描述", required = true, dataType = "UserInfo") //参数定义..类型..之类的,这是基础简单,其余的看api吧~