Spring boot配置 swagger的代碼怎么寫,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
在實際開發中我們作為后端總是給前端或者其他系統提供接口,每次寫完代碼之后不可避免的都需要去寫接口文檔,首先寫接口文檔是一件繁瑣的事,其次由接口到接口文檔需要對字段、甚至是排版等。再加上如果我們是為多個系統提供接口時可能還需要按照不同系統的要求去書寫文檔,那么有沒有一種方式讓我們在開發階段就給前端提供好接口文檔,甚至我們可以把生成好的接口文檔暴露出去供其他系統調用,那么這樣我只需要一份代碼即可。
1.導入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的開關,表示已經啟用Swagger
@Configuration // 聲明當前配置類
public class SwaggerConfiguration {
@Value("${swagger.basePackage}")
private String basePackage; // controller接口所在的包
@Value("${swagger.title}")
private String title; // 當前文檔的標題
@Value("${swagger.description}")
private String description; // 當前文檔的詳細描述
@Value("${swagger.version}")
private String version; // 當前文檔的版本
@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: 標題 #標題 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

關于Spring boot配置 swagger的代碼怎么寫問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。