0.導包
<!--配置swagger管理接口文檔-->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<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>
1.在需要掃描的controller層配置一個類
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.xxx.yy.web.controller"))
//包:就是自己接口的包路徑
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("xxx系統api")//名字
.description("xxx系統接口文檔說明")//額外藐視
.contact(new Contact("ww", "", "ee@163.com"))
.version("1.0")// 版本
.build();
}
}
2.在zuu中配置兩個類
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
@Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
//以后增加了接口就在這配置就ok
resources.add(swaggerResource("xx系統", "/xx/wg/v2/api-docs", "2.0"));
resources.add(swaggerResource("ss系統", "/xx/product/v2/api-docs", "2.0"));
resources.add(swaggerResource("qq系統", "/xx/common/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;
}
}
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("xx系統")
.description("xx系統接口文檔說明")
.contact(new Contact("ss", "", "ss@163.com"))
.version("1.0")
.build();
}
}
4.一般情況配置以上配置就可以正常使用swagger了,但由於一些版本問題導致出現:
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:
這個時候需要在配置類的啟動類中添加注解進行掃描即可:
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy//zuul
@ComponentScan("cn.xxx.aigou.swagger2")
//@EnableSwagger2
public class ZuulApplication9527 {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication9527.class);
}
}
