OSGI环境下Swagger @ApiModel与@ApiModelProperty注解失效问题问询
解决OSGI环境下Swagger v2模型注解不生效的问题
看起来你踩了Swagger注解版本混用+OSGI类加载的坑——你用了OpenAPI 3.x的接口注解(@Operation这类),但还在沿用Swagger 2.x的模型注解(@ApiModel/@ApiModelProperty),再加上OSGI特殊的类加载规则,直接导致模型字段描述、继承关系完全失效。下面是具体的解决方案:
1. 核心问题:注解版本不兼容
Swagger 2.x(io.swagger.annotations)和OpenAPI 3.x(io.swagger.v3.oas.annotations)是两套独立的注解体系,不能混用。你当前用了v3的接口注解,Swagger的扫描器只会识别v3的模型注解,旧的v2注解自然被忽略,这就是字段描述和继承关系失效的根本原因。
2. 迁移到OpenAPI 3.x的模型注解
把所有Swagger 2.x的模型注解替换为OpenAPI 3.x的@Schema注解,具体替换规则如下:
原v2代码:
@ApiModel(description = "foo - extends FooBase", parent = FooBase.class) public class Foo extends FooBase { @ApiModelProperty(value = "description") private String typeDescription; } @ApiModel(description = "foo", subTypes = {Foo.class, FooTwo.class}) public class FooBase { // 父类属性 }
替换为v3代码:
import io.swagger.v3.oas.annotations.media.Schema; @Schema(description = "foo - extends FooBase", allOf = {FooBase.class}) public class Foo extends FooBase { @Schema(description = "description") private String typeDescription; } @Schema(description = "foo", subTypes = {Foo.class, FooTwo.class}) public class FooBase { // 父类属性 }
@ApiModel→@Schema,继承关系用allOf属性指定父类@ApiModelProperty→@Schema的description属性
3. 更新依赖配置
移除旧的Swagger 2.x依赖,引入OpenAPI 3.x的官方依赖,同时注意OSGI环境的scope设置(尽量用compile而不是provided,避免类加载不到):
<!-- 移除旧的v2依赖 --> <!-- <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.0</version> <scope>provided</scope> </dependency> --> <!-- 引入OpenAPI 3.x核心依赖 --> <dependency> <groupId>io.swagger.core.v3</groupId> <artifactId>swagger-jaxrs2</artifactId> <version>2.2.15</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.swagger.core.v3</groupId> <artifactId>swagger-annotations</artifactId> <version>2.2.15</version> <scope>compile</scope> </dependency>
4. OSGI环境额外配置
OSGI的类加载机制可能会导致注解类无法被扫描到,需要做以下检查:
- 确保你的bundle的
Import-Package中包含io.swagger.v3.oas.annotations、io.swagger.v3.oas.annotations.media等包 - 如果使用Apache CXF或其他JAX-RS的OSGI实现,要确保Swagger的JAX-RS集成bundle(比如
swagger-jaxrs2)和你的JAX-RS版本兼容 - 检查bundle的启动级别,确保Swagger相关bundle在你的业务bundle之前启动
完成以上步骤后,重新生成API文档,模型字段的描述和继承关系应该就能正常显示了。
内容的提问来源于stack exchange,提问作者Tiago Machado
相关产品推荐
相关产品推荐

