You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot项目@ApiModel注解无法替换YAML配置占位符问题咨询

问题根因

你遇到的是SpringFox 2.9.2版本的已知功能缺失,该版本的核心处理逻辑里,仅对@ApiOperation、@ApiModelProperty两类注解的属性做了Spring环境占位符解析处理,未覆盖@ApiModel注解的description属性,因此会出现占位符直接透传显示的问题。

解决方案

方案1:升级SpringFox版本(推荐)

直接升级SpringFox到2.10.0及以上版本,官方在该版本中已经修复了@ApiModel的占位符解析问题。升级注意事项:

  • 2.10.0+版本调整了依赖的groupId和artifactId,需要替换原有springfox-swagger2、springfox-swagger-ui的依赖坐标
  • 原有配置类上的@EnableSwagger2注解需要替换为@EnableSwagger2WebMvc(适配SpringMVC场景)

方案2:低版本自定义扩展兼容(无需升级依赖)

如果不方便升级现有版本,可以自行实现SpringFox的ModelBuilderPlugin扩展点,手动解析@ApiModel注解中的占位符,示例代码如下:

import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertyResolver;
import com.fasterxml.classmate.ResolvedType;
import com.google.common.base.Optional;
import io.swagger.annotations.ApiModel;
import springfox.documentation.spi.schema.ModelBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

@Component
public class ApiModelPropertyResolver implements ModelBuilderPlugin {

    private final PropertyResolver propertyResolver;

    public ApiModelPropertyResolver(Environment environment) {
        this.propertyResolver = environment;
    }

    @Override
    public void apply(ModelContext context) {
        ResolvedType type = context.getType();
        Optional<ApiModel> annotation = Optional.fromNullable(type.getErasedType().getAnnotation(ApiModel.class));
        if (annotation.isPresent()) {
            String description = annotation.get().description();
            // 解析占位符
            String resolvedDesc = propertyResolver.resolveRequiredPlaceholders(description);
            context.getBuilder().description(resolvedDesc);
        }
    }

    @Override
    public boolean supports(springfox.documentation.spi.DocumentationType delimiter) {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }
}

将该类注册为Spring容器的组件后,即可自动解析@ApiModel中的占位符。

内容的提问来源于stack exchange,提问作者xenoid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 07:24:03