我們提供Restful接口的時候,API文檔是尤為的重要,它承載着對接口的定義,描述等。它還是和API消費方溝通的重要工具。在實際情況中由于接口和文檔存放的位置不同,我們很難及時的去維護文檔。個人在實際的工作中就遇到過很多接口更新了很久,但是文檔卻還是老版本的情況,其實在這個時候這份文檔就已經失去了它存在的意義。而Swagger是目前我見過的最好的API文檔生成工具,使用起來也很友善,還可以直接調試我們的API。我們今天就來看下Swagger2與SpringBoot的結合。
準備:
'io.springfox:springfox-swagger2:2.9.2'
'io.springfox:springfox-swagger-ui:2.9.2'
Swagger配置:
/**
* @author TanChong
* create date 2019\6\10 0010
*/
@Configuration
@EnableSwagger2
@ConditionalOnExpression("${swagger.enable}")
public class Swagger2Config extends WebMvcConfigurationSupport {
@Value("${swagger.enable}") private boolean enable;
@Bean
public Docket createAccepterRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("業務資料子產品API")//分組名,不指定預設為default
.select()
// .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.apis(RequestHandlerSelectors.basePackage("cn.waner.kexin.business_receiver"))// 掃描的包路徑
.paths(PathSelectors.any())// 定義要生成文檔的Api的url路徑規則
.build()
.apiInfo(apiInfo())// 設定swagger-ui.html頁面上的一些元素資訊
.enable(true);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("業務資料接收器RESTful API")
.description("提供業務資料接收子產品/業務資料處理子產品的文檔")
.termsOfServiceUrl("http://127.0.0.1:8080/")
.version("1.0")
.build();
}
//addResourceHandlers方法添加了兩個資源處理程式,
//這段代碼的主要作用是對Swagger UI的支援。(通路接口頁面為空白時可加上)
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
API文檔部分:
/**
* @author TanChong
* create date 2019\6\28 0028
*/
@RestController
@CrossOrigin
@Api(tags = "業務資料處理子產品API")
@RequestMapping("/api/v1/user_info_custodian")
public class UserInfoCustodianController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoCustodianController.class);
private UserInfoCustodianService userInfoCustodianService;
@Autowired
public UserInfoCustodianController(UserInfoCustodianService userInfoCustodianService) {
this.userInfoCustodianService = userInfoCustodianService;
}
@ApiOperation(value = "使用者監聽政策更新時響應")
@ApiImplicitParams({
@ApiImplicitParam(name = "configName",value = "政策比對url", required = true),
@ApiImplicitParam(name = "configUrl",value = "政策比對url", required = true),
@ApiImplicitParam(name = "assetsId",value = "資産ID", required = true)
})
@PostMapping("/unconventionality")
public void unconventionalityCustodian(@RequestBody AppUserConfigParam appUserConfigParam){
userInfoCustodianService.unconventionalityCustodian(appUserConfigParam);
}
}
這個Controller裡面多了很多新的注解,比如說@Api,@ApiOperation等,下面我們就來一一解釋一下
@Api,這個注解是用在Controller類上面的,可以對Controller做必要的說明。
@ApiOperation,作用在具體的方法上,其實就是對一個具體的API的描述。
@ApiParam,對API參數的描述。
到這裡,其實我們的Swagger就已經可以有效果了,讓我們将項目運作起來先看看效果。通路https://localhost:port/swagger-ui.html即可。
Model
在上面的圖中可以看到在頁面的下方有一個Models的标簽,這個就是我們API中出現的一些對象的文檔,我們也可以通過注解來對這些對象中的字段做一些說明,以友善使用者了解。
/**
* 政策模型參數
* [ 為什麼會存在這個模型? 别問 我就是想使用一下@RequestBody ]
* @author TanChong
* create date 2019\6\29 0029
*/
@ApiModel(description = "政策模型參數")
public class AppUserConfigParam {
//政策名稱
@ApiModelProperty(notes = "政策名稱") private String configName;
// 政策比對url
@ApiModelProperty(notes = "政策比對url") private String configUrl;
// 資産id
@ApiModelProperty(notes = "資産id") private String assetsId;
public String getConfigName() {
return configName;
}
public void setConfigName(String configName) {
this.configName = configName;
}
public String getConfigUrl() {
return configUrl;
}
public void setConfigUrl(String configUrl) {
this.configUrl = configUrl;
}
public String getAssetsId() {
return assetsId;
}
public void setAssetsId(String assetsId) {
this.assetsId = assetsId;
}
@Override
public String toString() {
return "AppUserConfigParam{" +
"configName='" + configName + '\'' +
", configUrl='" + configUrl + '\'' +
", assetsId='" + assetsId + '\'' +
'}';
}
}
誤區:
可能會有很大像我一樣粗心的猿,誤以為model類隻要添加了相關注解,在https://localhost:port/swagger-ui.html即可看到其詳細資訊,其實不然,隻有當你controller中使用到了次model,swagger才會幫你處理。就如以上接口中隻使用了AppUserConfigParam 是以我頁面上隻展示了AppUserConfigParam 這個model的詳情
現在我們對上文中展示的controller做一點點小修改
/**
* @author TanChong
* create date 2019\6\28 0028
*/
@RestController
@CrossOrigin
@Api(tags = "業務資料處理子產品API")
@RequestMapping("/api/v1/user_info_custodian")
public class UserInfoCustodianController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoCustodianController.class);
private UserInfoCustodianService userInfoCustodianService;
@Autowired
public UserInfoCustodianController(UserInfoCustodianService userInfoCustodianService) {
this.userInfoCustodianService = userInfoCustodianService;
}
@ApiOperation(value = "使用者監聽政策更新時響應")
@ApiImplicitParams({
@ApiImplicitParam(name = "configName",value = "政策比對url", required = true),
@ApiImplicitParam(name = "configUrl",value = "政策比對url", required = true),
@ApiImplicitParam(name = "assetsId",value = "資産ID", required = true)
})
@PostMapping("/unconventionality")
public void unconventionalityCustodian(@RequestBody AppUserConfigParam appUserConfigParam){
userInfoCustodianService.unconventionalityCustodian(appUserConfigParam);
}
// 新加入的接口 // 别找了 改動在這裡
@ApiModelProperty(value = "添加使用者監聽資料")
@PostMapping("/app_user")
public void createAppUsers(@RequestBody AppUsers appUsers){
}
}
使用到的Model:
/**
* @author TanChong
* create date 2019\6\28 0028
*/
@Document("app_users")
@ApiModel("描述")
public class AppUsers {
@Id
@ApiModelProperty("Objectid") private ObjectId id;
@Field("config_id")
@ApiModelProperty("政策ID") private ObjectId configId;
@Field("data_app_id")
@ApiModelProperty("業務資料ID") private ObjectId dataAppId;
@Field("users_name")
@ApiModelProperty("關鍵字") private String usersName;
@Field("users_auth_body")
@ApiModelProperty("政策主體") private String usersAuthBody;
@Field("insert_time")
@ApiModelProperty("資料插入時間") private Long insertTime;
}
現在我們重新開機項目再檢視一下頁面展示情況
好了文章到這裡就結束了,有什麼問題可以留言我們一起交流,覺得OK的話可以關注一下一起學習~_~