Swagger是一种框架,用于自动生成Restfull API的文档,而不用开发者自己编写文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。
以下以SpringBoot 2.0.1中整合Swagger2.8.0为例.
1、Maven:
<!-- swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency>
2、建立Swagger配置类
@Configuration @EnableSwagger2 public class SwaggerConfig implements WebMvcConfigurer { // 须不能被拦截的资源(包括请求的拦截、返回信息的拦截改造等),如不能被WebSecurity框架拦截 public static final List<String> RESOURCE_PATTERNS = Arrays.asList("/swagger-ui.html", "/webjars/**", "/swagger-resources/**", "/api-docs", "/v2/api-docs"); @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // API文档页面相关资源作为静态资源,以防止被拦截处理 registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); registry.addResourceHandler("/swagger-resources/**").addResourceLocations("classpath:/META-INF/resources/"); } private ApiInfo apiBasicInfo = new ApiInfoBuilder().title("SSEducationAdmin Server API").description("Spring Boot REST API for SSEducationAdmin").version("0.0.1") .license("Apache License Version 2.0").licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"") .contact(new Contact("San Zhang", "https://localhost:8082/", "zhangsan1@xx.com")).build(); private Parameter tokenHeaderParameter = new ParameterBuilder().name(BasicWebSecurityConfig.AUTHENTICATION_HEADER_NAME).description("接口调用认证及鉴权").modelRef(new ModelRef("string")) .parameterType("header").required(true).build(); //通过Docket进行API分组,通常根据业务模块来分组,这样可在swagger ui上选择这些分组看对应的API @Bean public Docket allApi() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiBasicInfo).globalOperationParameters(Arrays.asList(tokenHeaderParameter)).groupName("所有接口").select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any()).build(); } @Bean public Docket customerManageApi() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiBasicInfo).globalOperationParameters(Arrays.asList(tokenHeaderParameter)).groupName("客户管理接口").select() .apis(RequestHandlerSelectors.basePackage(CustomerAdmin_CustomerController.class.getPackage().getName()))// 指定扫描的包,其下Controller方法会生成文档 .paths(PathSelectors.any()).build(); } }