Springcloud项目中通过网关使用swagger
网关中添加相关依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.8.1</version>
</dependency>
编写swagger配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private DiscoveryClientRouteLocator discoveryClientRouteLocator;
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
;
}
private ApiInfo buildApiInfo() {
return new ApiInfoBuilder()
.title("接口文档")
.description("相关后台接口")
.contact("wei")
.version("1.0.0")
.build();
}
}
编写文档配置类
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
private final RouteLocator routeLocator;
@Autowired
private DiscoveryClient discoveryClient;
public DocumentationConfig(RouteLocator routeLocator) {
this.routeLocator = routeLocator;
}
@Value("${spring.application.name}")
private String applicationName;
@Override
public List<SwaggerResource> get() {
ArrayList<SwaggerResource> resources = new ArrayList<>();
discoveryClient.getServices().stream().filter(s ->
!s.equals(applicationName))
.forEach(name -> {
Optional<ServiceInstance> instanceOptional = discoveryClient.getInstances(name)
.stream().findFirst();
if (instanceOptional.isPresent() && instanceOptional.get().getMetadata().containsKey("context-path")) {
String contexPath = instanceOptional.get().getMetadata().get("context-path");
resources.add(swaggerResource(name, "/" + name + contexPath + "/v2/api-docs", "2.0"));
} else {
resources.add(swaggerResource(name, "/" + name + "/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;
}
}
访问网关的swagger-ui.html