關於使用swagger的問題


  近來在公司實現,接觸到不少新的工具框架,今天見識到了一個新的工具,它的存在好像是情理之中的,但是以前就沒有遇到這東西。那就是swagger,它的功能就是把你寫的controller的內容都集合到一起方便測試。或者說是把接口都集合在一起。什么樣的感覺?看圖就明白。

  有了它,感覺方便了很多,一個是不用打開postman之類的測試工具了,另一方面連路徑參數什么的都不用寫了,讓人興奮。

  介紹一下怎么安裝,我使用的是maven項目,maven項目在start.spring.io那里生成什么的都可以,至少加個web,然后在pom.xml添加上下面的代碼:

    <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>

  這把我遇到需要的都加上了。包括了一些需要用到的jar包什么的。

  接着寫個關於它的配置文件:  

@Configuration
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages = {"com.example.swagger.swagger"})
public class SwaggerConfig {

    ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("XXXX Web Selfservice APIs")
                .description("")
                .license("")
                .licenseUrl("")
                .termsOfServiceUrl("")
                .version("1.0.0")
                .build();
    }

    @Bean
    public Docket customImplementation() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.swagger.swagger"))
                .build()
                .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class)
                .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class)
                .apiInfo(apiInfo());
    }
}

  下一步是要增加它在項目的配置文件:

@Configuration
public class WebMVCConfig 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/");

    }
}

   最后就是寫一個controller了:

@Api(value = "controller信息")
@RestController
@EnableAutoConfiguration
@RequestMapping(value = "/api/index")
public class indexController {

    @ApiOperation(value = "測試swagger", notes = "這是一條注意信息")
    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }

}

   現在可以打開網址:http://localhost:8080/swagger-ui.html,見證它的神奇。


免責聲明!

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



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