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

如何从外部资源为@ExampleProperty注解提供值用于@ApiResponse配置

解决方案

Java注解的属性值要求是编译期常量,所以无法直接在注解中写入运行期变量,针对你用的Swagger框架版本不同,有以下几种实现方式:

方式1:SpringDoc v1.6.0+ 直接用占位符(最简方案)

SpringDoc 1.6.0及以上版本已经原生支持解析注解属性中的Spring配置占位符,你直接把配置的key写到@ExampleProperty的value中即可:

  1. 先在application.yml/application.properties中配置你的错误样例:
swagger:
  example:
    bad-request: "{\"400\": \"The format of field Value1 is invalid.\",\"400\": \"The format of field Value2 is invalid.\"}"
  1. 直接在注解中引用占位符:
@ApiResponses(value = {
        @ApiResponse(code = 200,message = "Successfully"),
        @ApiResponse(code = 400,
                     message = "Bad Request",
                     examples = @Example(value  ={
                             @ExampleProperty(mediaType = "application/json",value = "${swagger.example.bad-request}")
                            }))
})

框架会自动从配置文件读取对应值替换占位符。

方式2:自定义全局响应配置(全版本通用)

如果你用的是旧版本SpringDoc或者SpringFox,也可以通过自定义全局OpenAPI配置的方式,从配置文件读取值后动态注入响应样例,不需要在每个接口上硬编码:

  1. 读取配置文件的样例内容,这里用@Value注入为例:
@Value("${swagger.example.bad-request}")
private String badRequestExample;
  1. 构造自定义OpenAPI Bean(SpringDoc示例):
@Configuration
public class SwaggerConfig {
    @Value("${swagger.example.bad-request}")
    private String badRequestExample;

    @Bean
    public OpenAPI customOpenApi() {
        return new OpenAPI()
                .components(new Components()
                        .addResponses("400", new ApiResponse()
                                .description("Bad Request")
                                .content(new Content()
                                        .addMediaType("application/json", 
                                                new MediaType().example(Json.parse(badRequestExample))))))
                .info(new Info().title("接口文档").version("1.0"));
    }
}
  1. 接口上直接引用全局配置的响应即可,不需要重复写Example:
@ApiResponse(responseCode = "400", ref = "400")

方式3:编译期资源替换(静态替换场景适用)

如果你不需要运行时修改样例内容,只需要把硬编码抽离到外部配置文件,也可以用构建工具的资源过滤功能,在编译打包时把配置值替换到注解里,比如Maven的resource filtering功能可以直接替换Java文件中的${}占位符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:06:04