近来在公司实现,接触到很多新的工具框架,今天见识到了一个新的工具,它的存在好像是情理之中的,可是之前就没有遇到这东西。那就是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,见证它的神奇。框架