springboot项目中使用swagger,快速生成api
pom中引入
1 2 3 4 5 6 7 8 9 10 11
| <!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
|
swagger配置
支持在配置文件中配置是否显示api,需要显示api的接口uri。(此处使用到了在springboot中读取配置文件信息的知识。springboot读取配置文件)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| @EnableSwagger2 @Component public class Swagger2 { @Autowired private BasicProperties basicProperties; @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .enable(basicProperties.getSwaggerShow()) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.hfy")) // .paths(PathSelectors.any()) //.paths(PathSelectors.regex("/ab/*")) //.apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(path()) .build(); } private Predicate<String> path() { List<Predicate<String>> list = new ArrayList<>(); for (String pattern : basicProperties.getSwaggerPatterns()) { list.add(PathSelectors.regex(pattern)); } return Predicates.or(list); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("APIs") .contact("hfy") .version("1.0") .build(); } }
|
待完成
暂时没做到:swagger中搜索不可用。
参考
Spring Boot中使用Swagger2构建强大的RESTful API文档
SpringBoot项目生成RESTfull API的文档