【问题标题】:Dynamic JsonProperty using Jackson with Spring Boot将 Jackson 与 Spring Boot 结合使用的动态 JsonProperty
【发布时间】:2017-03-30 23:15:09
【问题描述】:

我开发了一个 Spring Boot 应用程序。此应用程序可以部署到测试或生产环境,该应用程序使用 REST API 发出请求。我使用 POJO 作为包装器,JsonProperty 注释包含 API 的字段 ID,它被推送到。

@JsonProperty("field_001)
private String name;

@JsonProperty("field_002)
private String address;

这些值的字段标签在测试端点上有所不同。所以测试端点可能期望属性映射为

@JsonProperty("field_005)
private String name;

@JsonProperty("field_006)
private String address;

我希望能够利用 Spring Boot 对基于配置文件的属性文件的原生支持。在运行时从外部属性文件中读取 JsonProperty 注释值。

例如,

可能存在三个文件 application.properties、application-test.properties 和 application-prod.properties。除了基于“spring.profiles.active”设置的普通属性文件之外,Spring Boot 还可以读取 test 或 prod 属性。

...-test.properties 将包含测试服务器字段的常量值。并且 ...-prod.properties 将包含 prod 服务器字段的常量值。

嵌套注解比如Spring的@Value标签,像这样:

@JsonProperty(@Value("${property.file.reference.here})) 
doesn't seem to work.

最好的问候

【问题讨论】:

  • 为什么您的报价都没有关闭?

标签: java spring spring-boot jackson


【解决方案1】:

@JsonProperty(@Value("${property.file.reference.here})) 无法正常工作,因为:

@JsonProperty 使用 String 作为值,但 @Value 是 'Annotation',所以这不是 String 值,写它会出现以下错误:

错误:(34, 12) java: 注解对于 java.lang.String 类型的元素无效

另外,@Value 将在 spring 上下文加载时加载“一次”。

编辑

如果你想使用 test/dev 和 prod 属性,最好在你的测试资源包下创建一个属性文件,它们会被自动加载。 (我就是这样用的)。

其实还有一种方法,就是在运行时修改注解值。

【讨论】:

  • 感谢 Mohamed ELAYADI。我不明白你知道如何处理我的测试资源包下的文件。我有两个文件:用于开发环境的 application.properties 和用于生产环境的另一个文件。
  • 不,我还在寻找。你有什么想法
猜你喜欢
  • 2016-05-07
  • 1970-01-01
  • 2017-02-01
  • 2022-11-30
  • 2019-09-14
  • 2016-09-24
  • 1970-01-01
  • 2020-06-22
  • 2014-02-20
相关资源
最近更新 更多