介绍
swagger 是一个定义接口文档及接口相关信息的工具, 通过这个工具可以生成各种形式的文档。作为 Java 大一统框架, 当然会将该规范纳入进来, 形成了 Spring-swagger, 现在改成了 Springfox, 那么接下来讲一讲如何引入这个东东。
依赖
pom.xml:
1 2 3 4 5 6 7 8 9 10
| <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger.version}</version> </dependency>
|
配置
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| package com.littleboy.config;
import com.google.common.base.Predicate; import com.littleboy.config.annotation.SwaggerCustomIgnore; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static com.google.common.base.Predicates.*; import static springfox.documentation.builders.RequestHandlerSelectors.*; import static springfox.documentation.builders.PathSelectors.*;
@Configuration @EnableSwagger2 @ComponentScan(basePackages = "com.littleboy.controller") public class SwaggerConfig { @Bean public Docket swaggerSpringMvcPlugin(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(swaggerDemoApiInfo()) .select() .apis(not(withMethodAnnotation(SwaggerCustomIgnore.class))) .paths(allowPaths()) .build(); }
private ApiInfo swaggerDemoApiInfo(){ Contact contact = new Contact("littleboy", "http://icecreamzhao.github.io", "dahazidk@163.com"); return new ApiInfoBuilder() .contact(contact) .title("Swagger2构建RESTful API文档") .description("SpringBoot集成Springbox开源项目,实现OAS,构建成RESTful API文档") .version("1.0.0") .build(); }
private Predicate<String> allowPaths(){ return or( regex("/user.*"), regex("/role.*") ); } }
|
SwaggerCustomIgnore:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package com.littleboy.config.annotation;
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;
@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface SwaggerCustomIgnore {
}
|
查看效果
启动项目, 访问http://localhost:8080/swagger-ui.html
就可以查看符合条件的接口文档了。