關於使用swagger的問題

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

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

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

    <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包什麼的。spring

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

@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());
    }
}

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

@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了:app

@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,見證它的神奇。框架

相關文章
相關標籤/搜索