二、SpringBoot 整合 swagger2 (swagger2 版本 2.8.0)
阿新 • • 發佈:2018-12-31
(一)新增依賴
<swagger.version>2.8.0</swagger.version>
<!-- swagger2 restful api 文件 start -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</ dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- swagger2 restful api 文件 end -->
(二)swagger2的配置啟動類
package com.tushuo.config;
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;
/**
* swagger2的配置檔案,這裡可以配置swagger2的一些基本的內容,比如掃描的包等等
* @author 鹹魚
* @date 2018/12/24 21:08
*/
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//api所在包路徑(這個包指的是我們在哪些類中使用swagger2來測試)
.apis(RequestHandlerSelectors.basePackage("com.tushuo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//頁面標題
.title("api文件")
//描述
.description("restful 風格介面")
//建立人
.contact(new Contact("鹹魚", "https://blog.csdn.net", " [email protected]"))
//版本號
.version("1.0")
.build();
}
}
(三)使用案例
1、新增相關注解
@RestController @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Api("測試 UserController 相關api") public class UserController { private final UserService userService; @ApiOperation(value = "儲存使用者", notes = "儲存使用者") @ApiImplicitParam(name = "user", value = "User", required = true, dataType = "User") @PostMapping("/user") public boolean addUser(@RequestBody User user) { return userService.save(user); } }
2、訪問http://localhost:8080/swagger-ui.html