一、springboot单应用配置swagger(简单)
1.添加依赖
// swagger2依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
// swagger2的ui
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.配置config
@EnableSwagger2
@Configuration
public class SwaggerConfig {
// 如果想要线上环境关掉swagger
private boolean swagger_is_enable = true;
// 解决方案
// 设置要显示的swagger环境
Profiles profiles = Profiles.of("dev","test");
// 通过environment.acceptsProfiles判断是否处在自己设定的环境当中
swagger_is_enable = environment.acceptsProfiles(profiles);
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
// enable是否启动swagger,如果为false,则swagger不能在浏览器中访问
.enable(swagger_is_enable)
.apiInfo(buildApiInf())
.select()
// swagger 扫描 controller 包路径
// RequestHandlerSelectors配置要扫描接口的方式
// basePackage:指定要扫描的包
// any():扫描全部
// none():不扫描
// withClassAnnotation:扫描类上的注解,参数是一个注解的反射对象
// withMethodAnnotation:扫描方法上的注解
.apis(RequestHandlerSelectors.basePackage("com.yywd.select.controller"))
// 过滤接口
// PathSelectors.ant("/kuang/**") 只显示匹配/kuang/**的接口
.paths(PathSelectors.any())
.build().groupName("查询模块");
}
private ApiInfo buildApiInf() {
//Contact contact = new Contact("xxx", "", "");
return new ApiInfoBuilder()
.title("院校选择模块API")
//.contact
.description("该模块属于考研咨询的基本模块之一")
.version("1.0")
.build();
}
}
二、springcloud微服务网关配置swagger
1.添加依赖
在common模块中添加依赖,在各个模块中依赖common
2.各个模块配置config参考上文
3.gateway配置
- 转发路由
spring:
cloud:
gateway:
routes:
- id: xxx
uri: lb://yywd-select
predicates:
- Path=/api/select/**
filters:
# 两者选其一即可(用来去掉路径中第一个api)
- RewritePath=/api/(?<segment>.*),/$\{segment}
- StripPrefix=1
- id: xxx
uri: lb://yywd-third-party # lb是Load balancing,转发路由
predicates:
- Path=/api/thirdparty/** #匹配规则
filters:
- RewritePath=/api/(?<segment>.*),/$\{segment} # 重写规则
- StripPrefix=1
- id: admin_route # 务必放在最下面
uri: lb://renren-fast
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<segment>.*),/renren-fast/$\{segment}
- swaggerConfig
@Primary
@Configuration
public class SwaggerConfig implements SwaggerResourcesProvider {
public static final String API_URI = "/v2/api-docs";
private final RouteLocator routeLocator;
private final GatewayProperties gatewayProperties;
public SwaggerConfig(RouteLocator routeLocator, GatewayProperties gatewayProperties) {
this.routeLocator = routeLocator;
this.gatewayProperties = gatewayProperties;
}
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
List<String> routes = new ArrayList<>();
//取出gateway的route
routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
//结合配置的route-路径(Path),和route过滤,只获取有效的route节点
gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
.forEach(routeDefinition -> routeDefinition.getPredicates().stream()
.filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
.forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
.replace("/**", API_URI)))));
return resources;
}
private SwaggerResource swaggerResource(String name, String location) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion("2.0");
return swaggerResource;
}
}
- swaggerHandler
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerHandler {
@Autowired(required = false)
private SecurityConfiguration securityConfiguration;
@Autowired(required = false)
private UiConfiguration uiConfiguration;
private final SwaggerResourcesProvider swaggerResources;
@Autowired
public SwaggerHandler(SwaggerResourcesProvider swaggerResources) {
this.swaggerResources = swaggerResources;
}
@GetMapping("/configuration/security")
public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("/configuration/ui")
public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
return Mono.just(new ResponseEntity<>(
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
}
@GetMapping("")
public Mono<ResponseEntity> swaggerResources() {
return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
}
}
三、常用注解
- 放在类上
@Api(tags = "专业模块的后端接口")
public class MajorController {}
- 放在方法上
// value 为简短说明,一般这个就可以,notes 为详细说明
@ApiOperation(value = "查询所有专业", notes = "查出所有分类以及子分类列表,以树形结构组装起来")
// 说明参数,2.9.2版本的swagger要标明example属性,否则会报异常,paramType表示参数的提供方式
@ApiImplicitParam(name = "type", required = true, dataType = "int", paramType = "path", value = "类型", example = "0")
@GetMapping("/list/tree/{type}")
public R list(@PathVariable("type") Integer type) {}
/**
* paramType:表示参数放在哪个地方
header-->请求参数的获取:@RequestHeader(代码中接收注解)
query-->请求参数的获取:@RequestParam(代码中接收注解)
path(用于restful接口)-->请求参数的获取:@PathVariable(代码中接收注解)
body-->请求参数的获取:@RequestBody(代码中接收注解)
form(不常用)
*/
// 如果多个参数
@ApiImplicitParams({
@ApiImplicitParam(name = "type", required = true, dataType = "int", paramType = "path", value = "类型", example = "0"),
@ApiImplicitParam(name = "id", required = true, dataType = "int", paramType = "path", value = "父类id", example = "0")
})
- 放在实体类上
@ApiModel(value = "专业实体类", description = "最全最完整的专业对象") 一般只需要这个就可以
public class MajorEntity{
@ApiModelProperty(value = "专业id", example = "1", required = true)
private Integer majorId;
@ApiModelProperty(hidden = true)
private Integer majorName;
}