1.首先需要在对应的服务中进行导包:
<!--引入swagger支持--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
2.添加成为spring的容易信息,启动的使用,并且修改要生成的服务路径:
package cn.itsource.hrm.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; 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; @Configuration @EnableSwagger2 // 开启Swagger public class Swagger2 { //把对象交给spring管理 @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //对外暴露服务的包,以controller的方式暴露,所以就是controller的包. 指定是哪些POM对应包的路径 .apis(RequestHandlerSelectors.basePackage("cn.itsource.hrm.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("系统服务api") .description("系统服务接口文档说明") .contact(new Contact("luy668", "http:www.baidu.com", "mlg@itsource.cn")) .version("1.0") .build(); } }
3.根据服务的端口访问swagger即可:
4.集成到网关中,多了一个配置类:
package cn.itsource.hrm.config; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; import springfox.documentation.swagger.web.SwaggerResource; import springfox.documentation.swagger.web.SwaggerResourcesProvider; import java.util.ArrayList; import java.util.List; @Component @Primary public class DocumentationConfig implements SwaggerResourcesProvider { @Override public List<SwaggerResource> get() { // 将所有的服务swagger地址交给网关管理 List resources = new ArrayList<>(); resources.add(swaggerResource("系统管理", "/hrm/system/sysmanage/v2/api-docs", "2.0")); resources.add(swaggerResource("系统管理1", "/services/sysmanage/v2/api-docs", "2.0")); resources.add(swaggerResource("系统管理2", "/services/sysmanage/v2/api-docs", "2.0")); return resources; } private SwaggerResource swaggerResource(String name, String location, String version) { SwaggerResource swaggerResource = new SwaggerResource(); swaggerResource.setName(name); swaggerResource.setLocation(location); swaggerResource.setSwaggerVersion(version); return swaggerResource; } }
可以选择多个服务