您的位置:首页 > 编程语言 > Java开发

Spring Boot中使用Swagger2构建RESTful API文档

2016-12-02 00:00 405 查看
随着前后端的分离,借口文档变的尤其重要,今天我们来说一说用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就萌逼了,目前还没找到解决方案。

dome:https://github.com/maomaolsm/spring-boot-swagger2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Swagger