Spring boot配置 swagger的示例代碼
為什么使用Swagger
在實際開發(fā)中我們作為后端總是給前端或者其他系統(tǒng)提供接口,每次寫完代碼之后不可避免的都需要去寫接口文檔,首先寫接口文檔是一件繁瑣的事,其次由接口到接口文檔需要對字段、甚至是排版等。再加上如果我們是為多個系統(tǒng)提供接口時可能還需要按照不同系統(tǒng)的要求去書寫文檔,那么有沒有一種方式讓我們在開發(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: 項目文檔 #描述 version: V1.0 #版本號
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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一步步教你JAVA如何優(yōu)化Elastic?Search
想要榨干Java操作Elasticsearch的所有性能潛力?本指南將一步步教你如何優(yōu)化Java與Elasticsearch的交互!從此,提升ES查詢速度、降低資源消耗不再是難題,趕快一起來探索Java?Elasticsearch優(yōu)化的秘訣吧!2024-01-01
解決myBatis generator逆向生成沒有根據(jù)主鍵的select,update和delete問題
這篇文章主要介紹了解決myBatis generator逆向生成沒有根據(jù)主鍵的select,update和delete問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
使用Spring?Boot如何限制在一分鐘內(nèi)某個IP只能訪問10次
有些時候,為了防止我們上線的網(wǎng)站被攻擊,或者被刷取流量,我們會對某一個ip進行限制處理,這篇文章,我們將通過Spring?Boot編寫一個小案例,來實現(xiàn)在一分鐘內(nèi)同一個IP只能訪問10次,感興趣的朋友一起看看吧2023-10-10

