SpringBoot整合Swagger
導入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蒸苇,創(chuàng)建SwaggerConfig.java類
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;
// 配置類
@Configuration
//注解開啟 swagger2功能
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.groupName("swaggerText")
.select()
// 掃描的路勁包,設置basePackage會將包下的所有被@Api標記類的所有方法作為api
.apis(RequestHandlerSelectors.basePackage("com"))
// 指定路徑處理PathSelectors.any()表示所有的路徑
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("這里是APi文檔名稱")
.description("這里是對api的接口描述")
//服務條款
.termsOfServiceUrl("https://gitee.com/S760620329")
//聯(lián)系信息
.contact(new Contact("笑一笑","https://gitee.com/S760620329","760620329@qq.com"))
.version("1.0").build();
}
}
創(chuàng)建controller哮洽,測試運行
@RestController
@RequestMapping("/text")
@Api(value = "測試接口", tags = "textController")
public class TextController {
@ApiOperation(value = "獲取id", notes = "根據(jù)url的id來獲取詳細信息")
/*
paramType:指定參數(shù)放在哪個地方
path:用于restful接口-->請求參數(shù)的獲忍钋:@PathVariable
*/
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long", paramType = "path")
@GetMapping("/{id}")
public String annotate(@PathVariable int id) {
return "you id is :" + id;
}
}
在啟動類上添加注解
@ComponentScan(basePackages = {"com.xujc"}) // 掃描swagger所在的包
@EnableSwagger2 // 開啟swagger
啟動Swagger
訪問 http://localhost:8080/swagger-ui.html 即可看到 Swagger-UI
常用注解說明
@Api:用于controller類上,說明該類的作用
- tags:"說明該類的作用鸟辅,可以在ui界面上看到的注解"
- value:"該參數(shù)沒有意義,在ui界面上也看不到莺葫,所以不需要配置"
@ApiOperation:用在controller的方法上匪凉,用來說明方法用途、作用
- value= "說明方法的用途捺檬、作用"
- notes= "方法的備注說明"
@ApiParam:用來給controller的參數(shù)增加說明
- name:參數(shù)名
- value:參數(shù)的漢字說明再层、解釋
- required:參數(shù)是否必傳,true必傳
@ApiModelProperty:用于entity堡纬、vo類上聂受; 表示對model屬性的說明或者數(shù)據(jù)操作更改
- value:字段說明
- example:舉例說明
@ApiIgnore:使用該注解忽略這個Api,不會生成接口文檔烤镐,可注解才類和方法上