1.Swagger自動生成HTML文檔
在springboot項目中導入依賴
<!--利用Swagger生成HTML文檔-->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
在啓動類上加上@EnableSwagger2註解,啓動項目,訪問http://localhost:8002/swagger-ui.html
即可查看所有接口。
對接口進行描述
@RequestMapping(value = "/",method = RequestMethod.GET)
@ApiOperation("前往首頁")//對Swagger2生成的接口進行一個描述
public String root(){
return "redirect:index";
}
在實體類中對返回的數據對象的屬性進行描述:
@ApiModelProperty(value="用戶的介紹屬性")
private String description;
在RESTful風格中解釋傳入的數據
@GetMapping("/{id}/deletion") public ModelAndView delete(Model model,@PathVariable("id") @ApiParam("傳入一個博客的id") Integer id){ System.out.println("controller。。。"); blogService.deleteBlog(id); model.addAttribute("blogsList",blogService.getBlogs()); return new ModelAndView("blog/list","blogModel",model); }
2.WireMock快速僞造RESTful服務
前端並行開發的時候,我們給它提供了一套僞造的RESTful服務,避免了app,pc端,小程序開發人員 ,對接口的理解不一致,寫的假的接口不一致 ,最好不好對接後臺。
swagger的使用必須在該服務開發測試好了,才能給前端來瀏覽swagger來調用。
1.下載,運行 jar
官網==》doc ==》running-standalone 作爲一個獨立服務器運行
$ java -jar wiremock-standalone-2.23.2.jar
2.在項目中添加依賴
<dependency> <groupId>com.github.tomakehurst</groupId> <artifactId>wiremock</artifactId> <version>2.22.0</version> </dependency>
不要加入scope爲test環境,否者在主函數中找不到jar
3.編寫運行函數
import com.github.tomakehurst.wiremock.client.WireMock; //相當於一個wiremock的客戶端 public class Test { public static void main(String[] args) { // System.out.println(new BCryptPasswordEncoder().encode("123456")); WireMock.configureFor(8000);//連接8000端口的服務器 WireMock.removeAllMappings();//清空以前的服務 ////向服務器發送get請求的接口服務,返回json串和200狀態碼 WireMock.stubFor( WireMock.get( WireMock.urlPathEqualTo("/order/1")) .willReturn(WireMock.aResponse().withBody("{\"id\":1}").withStatus(200))); } }
運行在服務器上訪問該僞服務接口
簡化代碼:
public class MockServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
configureFor(8062);
removeAllMappings();
mock("/order/1", "01");
mock("/order/2", "02");
}
private static void mock(String url, String file) throws IOException {
ClassPathResource resource = new ClassPathResource("mock/response/" + file + ".txt");
String content = StringUtils.join(FileUtils.readLines(resource.getFile(), "UTF-8").toArray(), "\n");
stubFor(get(urlPathEqualTo(url)).willReturn(aResponse().withBody(content).withStatus(200)));
}
}