一、Swagger2介紹
前后端分離開發模式中,api檔案是最好的溝通方式,
Swagger 是一個規范和完整的框架,用于生成、描述、呼叫和可視化 RESTful 風格的 Web 服務,
- 及時性 (介面變更后,能夠及時準確地通知相關前后端開發人員)
- 規范性 (并且保證介面的規范性,如介面的地址,請求方式,引數及回應格式和錯誤資訊)
- 一致性 (介面資訊一致,不會出現因開發人員拿到的檔案版本不一致,而出現分歧)
- 可測性 (直接在介面檔案上進行測驗,以方便理解業務)
二、配置Swagger2
1、引入相關依賴
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2、創建swagger的配置類
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("XX平臺API檔案")
.description("本檔案描述了xxx介面定義")
.version("1.0")
// 創建人
.contact(new Contact("Jade", "http://jade.com", "[email protected]"))
.build();
}
}
3、在啟動類上添加注解掃描swagger的配置類,進行測驗
要能掃描到swagger的配置類SwaggerConfig
@SpringBootApplication
// 要能掃描到swagger的配置類SwaggerConfig
@ComponentScan(basePackages = {"com.jade"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4、API模型
可以添加一些自定義設定,例如:
定義樣例資料
@ApiModelProperty(value = "https://www.cnblogs.com/jadite/p/創建時間", example = "2019-01-01 8:00:00")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "https://www.cnblogs.com/jadite/p/更新時間", example = "2019-01-01 8:00:00")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;

5、定義介面說明和引數說明
定義在類上:@Api
定義在方法上:@ApiOperation
定義在引數上:@ApiParam
@Api(description="講師管理")
@RestController
@RequestMapping("/admin/edu/teacher")
public class TeacherAdminController {
@Autowired
private TeacherService teacherService;
@ApiOperation(value = "https://www.cnblogs.com/jadite/p/所有講師串列")
@GetMapping
public List<Teacher> list(){
return teacherService.list(null);
}
@ApiOperation(value = "https://www.cnblogs.com/jadite/p/根據ID洗掉講師")
@DeleteMapping("{id}")
public boolean removeById(
@ApiParam(name = "id", value = "https://www.cnblogs.com/jadite/p/講師ID", required = true)
@PathVariable String id){
return teacherService.removeById(id);
}
}
6、測驗,查看效果
訪問http://localhost:8080/swagger-ui.html 即可

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/507130.html
標籤:Java
上一篇:Java代碼中如何判斷一個字串中是否包含特殊字符呢?
下一篇:一文快速了解Nacos
