大忙人系列_springboot簡單使用swagger生成接口文檔

第一步(*):引入swagger的依賴。springboot版本

        <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
	</parent>
	<!-- 統一管理依賴 -->
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Finchley.M7</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<dependencies>
		<!-- SpringBoot整合Web組件 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- swagger2 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.8.0</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.8.0</version>
		</dependency>
	</dependencies>
	<!-- 注意: 這裏必須要添加, 否者各種依賴有問題 -->
	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/libs-milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>

第二步(*):添加swagger配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Bean
    public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
				.apis(RequestHandlerSelectors.basePackage("掃包範圍")).paths(PathSelectors.any()).build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("xxxxx接口標題頭").description("接口介紹")
				.termsOfServiceUrl("條款地址")
				.version("接口版本").build();
	}
}

第三步(*):在controller類上添加註解@Api("接口類描述")

第四步:在方法上添加@ApiOperation("改接口描述")、@ApiImplicitParam(name="參數",value = "參數介紹",required=true(是否必填))

第五步(*):訪問地址http://ip:port/path/swagger-ui.html#/

訪問效果

點擊該接口以後,如下圖

第六步:在線調試

至此,最簡單的swagger文檔接口生成成功...

總結:在controller中,所有的方法最好是有具體的請求方法(post、get...等等),因爲如果我們不設置具體的請求方法以後swagger會認爲我們該接口支持所有的請求。會在Swagger中不方便管理。

API總結:

API詳細說明

@ApiImplicitParam

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章