分布式项目整合springfox-swagger
一:目的
结合分布式思想,将swagger整合到项目中。即一个swagger-ui界面展示多个服务的jsob数据。
二:技术栈
springboot+springfox-swagger
三:实现方法
1、创建一个简单springboot应用(swagger-ui)
①、添加依赖:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version></dependency><!-- swagger-ui --><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version></dependency>
②、项目启动类上添加注释:
@EnableSwagger2
③、修改配置项
将需要使用到的swagger api地址配置进SwaggerResource中
@Configurationpublic class SwaggerWsEndpointsConfig { @Primary @Bean public SwaggerResourcesProvider swaggerResourcesProvider(InMemorySwaggerResourcesProvider defaultResourcesProvider) { return () -> { SwaggerResource wsResource = new SwaggerResource(); wsResource.setName("server-name"); wsResource.setSwaggerVersion("2.0"); wsResource.setLocation("http://host:port/v2/api-docs"); List<SwaggerResource> resources = new ArrayList<>(defaultResourcesProvider.get()); resources.add(wsResource); return resources; }; }}
2、修改需要使用swagger-ui的服务
①、在这些服务的启动类上添加注释
@EnableSwagger2
②、添加配置项
@Configurationpublic class SwaggerConfig { @Bean public Docket petApi() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); }}
③、解决cors
@Configurationpublic class CORSConfiguration implements WebMvcConfigurer { @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues(); config.setAllowCredentials(false); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; }}