1. 程式人生 > >SpringBoot整合Swagger2簡單的例子

SpringBoot整合Swagger2簡單的例子

設定 tro -c fault rip comment sed itl java

Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單。

這裏我給大家帶來一個簡單的整合DEMO 先來看項目結構

下面是基本的步驟

一.添加MAVEN依賴

  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-swagger2</artifactId>
  4. <version>2.2.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.springfox</groupId>
  8. <artifactId>springfox-swagger-ui</artifactId>
  9. <version>2.2.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.codehaus.jackson</groupId>
  13. <artifactId>jackson-core-asl</artifactId>
  14. <version>1.9.13</version>
  15. </dependency>

二.編寫Swagger配置類

  1. @Configuration
  2. @EnableSwagger2
  3. public class Swaggers {
  4. @Bean
  5. public Docket swaggerSpringMvcPlugin() {
  6. ApiInfo apiInfo = new ApiInfo("sample of springboot", "sample of springboot", null, null, null, null, null);
  7. Docket docket = new Docket(DocumentationType.SWAGGER_2).select().paths(regex("/user/.*")).build()
  8. .apiInfo(apiInfo).useDefaultResponseMessages(false);
  9. return docket;
  10. }
  11. /*private ApiInfo apiInfo() {
  12. return new ApiInfoBuilder().title("測試API")
  13. .description("樊亞的測試API1")
  14. .version("1.0.0")
  15. .build();
  16. }*/
  17. /* @Bean
  18. public Docket createRestApi() {
  19. return new Docket(DocumentationType.SWAGGER_2)
  20. .apiInfo(apiInfo())
  21. .select()
  22. .apis(RequestHandlerSelectors.basePackage("com.didispace.web"))
  23. .paths(regex("/user/.*"))
  24. .build();
  25. }
  26. */
  27. }

當然也可以用鏈式編程的方法實現,這裏我使用的是NEW

三.編寫Controller

  1. @RestController
  2. @RequestMapping("/user")
  3. @Api(value = "Shop")
  4. public class SpringBootController {
  5. @ApiOperation(value = "獲取helloWorld", notes = "簡單SpringMVC請求")
  6. @RequestMapping("/")
  7. String home() {
  8. return "HELLO WORLD";
  9. }
  10. @ApiOperation(value = "獲得A+B", notes = "根據url的classNo和url的studentName獲得請求參數的字符串相加,RestFul風格的請求")
  11. @ApiImplicitParams({@ApiImplicitParam(name = "classNo", value = "班級編號", required = true, dataType = "String"),
  12. })
  13. @RequestMapping(value = "/class/{classNo}/to/{studentName}", method = RequestMethod.GET)
  14. String world(@PathVariable("classNo") String classNo, @PathVariable("studentName") String studentName) {
  15. return classNo + " " + studentName;
  16. }
  17. }

四.編寫Application載入類


  1. @SpringBootApplication
  2. public class Application {
  3. public static void main(String[] args) {
  4. SpringApplication.run(Application.class,args);
  5. }
  6. }

Swagger會默認把所有Controller中的RequestMapping方法都生成API出來,實際上我們一般只需要標準接口的(像返回頁面的那種Controller方法我們並不需要),所有你可以按下面的方法來設定要生成API的方法的要求。

至此功能基本實現了,我們可以通過訪問地址http://localhost:8080/swagger-ui.html/

查看生成好的API

SpringBoot整合Swagger2簡單的例子