swagger ui demo


前言

  前幾天一個朋友公司在用Springboot集合swagger時候總是從瀏覽器看不了接口,我兩找了問題,但是他還是沒有找到,於是我就自己從http://start.spring.io/上下載了一個demo,然后做一個swagger小集成,這個應該很簡單的。自己嘗試了一下,然后做個總,具體也就這三步。之后的業務,自己再結合自己公司項目一步一步加上去,可能一開始的demo是簡單的,但是首先要保證第一步沒問題了,之后有問題,那就說明是之后加的東西出了問題。

正文

  第一步:項目引入jar包路徑,我用的是gradle項目。

      compile 'io.springfox:springfox-swagger2:2.7.0'
      compile 'io.springfox:springfox-swagger-ui:2.7.0'

     第二步:啟動項中需要initApi的方法這個是必要的。感覺東西就這些,話不用說太多,見代碼。

      @EnableSwagger2
      @SpringBootApplication
      public class DemoApplication {

        public static void main(String[] args) {
          SpringApplication.run(DemoApplication.class, args);
        }
        @Bean
        public Docket initApi() {
          return new Docket(DocumentationType.SWAGGER_2)
             .enable(true)
             .apiInfo(demoApiInfo())
             .select()
             .apis(RequestHandlerSelectors.any())
             .build();
        }

        private ApiInfo demoApiInfo() {
          Contact contact = new Contact("xxx", "http://xxx", "xxxx");
          return new ApiInfoBuilder()
             .title("測試API")
            .description("REST風格API")
            .termsOfServiceUrl("http:xxx.xx.com")
            .contact(contact)
            .version("1.0")
            .build();
       }
    }

  第三步:就是我們要寫一個controller也就是api的地方。

      @RestController
      @RequestMapping(path = "/test")
      @Api(tags = {"test"})
      public class TestController {
        @GetMapping
        @ApiOperation(value = "測試")
        public String test() {
          return "testok";
         }
      }

  之后就可以啟動我們的項目了,通過8080/swagger-ui.html訪問我們的接口地址,這樣就完成了。

  

 

 

 

                  Believe that life is getting better


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM