Spring boot配置 swagger的示例代碼
為什么使用Swagger
在實(shí)際開發(fā)中我們作為后端總是給前端或者其他系統(tǒng)提供接口,每次寫完代碼之后不可避免的都需要去寫接口文檔,首先寫接口文檔是一件繁瑣的事,其次由接口到接口文檔需要對(duì)字段、甚至是排版等。再加上如果我們是為多個(gè)系統(tǒng)提供接口時(shí)可能還需要按照不同系統(tǒng)的要求去書寫文檔,那么有沒有一種方式讓我們?cè)陂_發(fā)階段就給前端提供好接口文檔,甚至我們可以把生成好的接口文檔暴露出去供其他系統(tǒng)調(diào)用,那么這樣我只需要一份代碼即可。
Spring boot配置 swagger
1.導(dǎo)入maven依賴
<!--配置swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<!--swagger第三方ui-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
2.swagger配置類
@EnableSwagger2 // Swagger的開關(guān),表示已經(jīng)啟用Swagger
@Configuration // 聲明當(dāng)前配置類
public class SwaggerConfiguration {
@Value("${swagger.basePackage}")
private String basePackage; // controller接口所在的包
@Value("${swagger.title}")
private String title; // 當(dāng)前文檔的標(biāo)題
@Value("${swagger.description}")
private String description; // 當(dāng)前文檔的詳細(xì)描述
@Value("${swagger.version}")
private String version; // 當(dāng)前文檔的版本
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.version(version)
.build();
}
}
3.application.yml
# 配置swagger swagger: basePackage: com.xx.demo.controller #包名 title: 標(biāo)題 #標(biāo)題 description: 項(xiàng)目文檔 #描述 version: V1.0 #版本號(hào)
4.在controller里使用
@Api(tags = {"測試類"})
@RestController
@RequestMapping("/test")
public class TestController {
@ApiOperation(value = "測試方法")
@GetMapping("/xrx")
public String xrx() {
return "hello";
}
}
5.訪問swagger
http://localhost:8080/swagger-ui.html
http://localhost:8080/doc.html

到此這篇關(guān)于Spring boot配置 swagger的示例代碼的文章就介紹到這了,更多相關(guān)Spring boot配置 swagger內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring使用Filter過濾器對(duì)Response返回值進(jìn)行修改的方法
這篇文章主要介紹了spring使用Filter過濾器對(duì)Response返回值進(jìn)行修改,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09
Java設(shè)計(jì)模式中組合模式應(yīng)用詳解
組合模式,又叫部分整體模式,它創(chuàng)建了對(duì)象組的數(shù)據(jù)結(jié)構(gòu)組合模式使得用戶對(duì)單個(gè)對(duì)象和組合對(duì)象的訪問具有一致性。本文將通過示例為大家詳細(xì)介紹一下組合模式,需要的可以參考一下2022-11-11
intellij idea設(shè)置統(tǒng)一JavaDoc模板的方法詳解
這篇文章主要介紹了intellij idea設(shè)置統(tǒng)一JavaDoc模板的方法詳解,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04

