swagger2 API文件的框架 配置
阿新 • • 發佈:2019-02-16
隨著網際網路技術的發展,現在的網站架構基本都由原來的後端渲染,變成了:前端渲染、先後端分離的形態,而且前端技術和後端技術在各自的道路上越走越遠。
前端和後端的唯一聯絡,變成了API介面;API文件變成了前後端開發人員聯絡的紐帶,變得越來越重要,swagger
就是一款讓你更好的書寫API文件的框架。
pom.xml 新增依賴
<!-- Restful API介面說明 生成 swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.5.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.5.0</version> <scope>compile</scope> </dependency>
controller內容
@RequestMapping(value = "/per/{id}", method = RequestMethod.GET) @ApiOperation(value = "測試", notes = "測試逆向工程") public ResultVO selectByPrimaryKey(@PathVariable("id")Integer id) { per perLIst= userservice.selectByPrimaryKey(id); return ResultVOUtil.success(perLIst); }
swagger2檔案內容
import io.swagger.annotations.ApiOperation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2 extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("文件") .description("提供給外部系統的服務介面,進行管理業務。") .termsOfServiceUrl("http://terms-of-services.url") .version("1.0") .build(); } }
訪問地址:http://localhost:8085/swagger-ui.html
可以測試很方便 點Try it out!
我的demo用的事JSON傳資料 用的RESTful風格 get 查詢 post 建立 put 更新 del 刪除 都可以測試