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

随着先后端的分离,借口文档变的尤为重要,今天咱们来讲一说用SWAGGER2,来风骚的生成api文档。配置很简单,废话少说,直接上代码:java

build.gradlegit

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.javagithub

@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.javaweb

@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/spring

可是我也发现有个坑,就是若是url带加密协议,swagger就萌逼了,目前还没找到解决方案。后端

dome:https://github.com/maomaolsm/spring-boot-swagger2api

相关文章
相关标签/搜索