Spring Boot中使用Swagger2构建RESTful API文档
文章目录
随着前后端的分离,借口文档变的尤其重要,今天我们来说一说用SWAGGER2,来风骚的生成api文档。配置很简单,废话少说,直接上代码:
build.gradle
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile('org.springframework.boot:spring-boot-starter-web')
compile('io.springfox:springfox-swagger2:2.2.2')
compile('io.springfox:springfox-swagger-ui:2.2.2')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
SwaggerConfig.java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket testApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("test")
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(true)
.pathMapping("/")// base,最终调用接口后会和paths拼接在一起
.select()
.apis(RequestHandlerSelectors.basePackage("com.example"))
.build();
}
}
DemoApplication.java
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@ApiOperation("test")
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {
return "success!";
}
@ApiOperation("test2")
@RequestMapping(value = "/test2", method = RequestMethod.GET)
public String test2(@RequestParam String param) {
return "Running : " + param;
}
}
对,就是这么简单,这个就能满足正常的开发需要了,但SWAGGER的强大不仅仅是这些,有需要可以查看官方文档http://swagger.io/
但是我也发现有个坑,就是如果url带加密协议,swagger就萌逼了,目前还没找到解决方案。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论