一般在有controller层的模块集成swagger;废话不多说,直接看步骤。
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.主要起作用的类 Swagger2
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//对外暴露服务的包,以controller的方式暴露,所以就是controller的包.
.apis(RequestHandlerSelectors.basePackage("cn.zzq.system.web.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("系统管理服务api")
.description("系统管理服务接口文档说明")
.contact(new Contact("zzq", "", "zzq@itsource.cn"))
.version("1.0")
.build();
}
}
3.测试
项目地址:http://ip:端口/swagger-ui.html
在网关模块中配置
1.导包
<!-- 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>
2.SwaggerResourcesProvider类
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
//整合每个微服务的swagger
@Override
public List<SwaggerResource> get() {
List resources = new ArrayList<>();
//一个 SwaggerResource对应一个微服务 : 参数: 服务中文名 , 路径:/zuul前缀/服务的routes访问路径//v2/api-docs ; 版本
resources.add(swaggerResource("系统管理", "/hrm/system/v2/api-docs", "2.0"));
resources.add(swaggerResource("课程管理", "/hrm/course/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;
}
}
3.SwaggerConfig类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("分布式人力资源综合平台")
.description("人力资源综合平台接口文档说明")
.termsOfServiceUrl("http://localhost:1020") //zuul的地址
.contact(new Contact("zzq", "", "zzq@itsoruce.cn"))
.version("1.0")
.build();
}
}
关注公众号,获取免费软件、资料,笔记等。