首页 > 解决方案 > 如何根据活动配置文件控制是否应使用 Spring Boot 序列化字段

问题描述

我一直在寻找一种方法,能够在 Spring Boot 中使用自定义注释来注释我的响应模型,以控制应该使用 spring 配置文件和 Jackson 序列化哪个字段。

我知道有一个现有的注释 JsonView 来定义不同的视图,但这需要逻辑来处理启用它们的每个模型的单独视图。

我宁愿使用自定义注释,该注释将采用(列表)配置文件来排除/包含该字段。

我还考虑编写一个序列化器,但它只控制值,而不是整个属性,包括名称。

这在某种程度上可能吗?

class Response {

    var message: String

    @JsonExclude("production")
    var debugMessage: String? = null
}

标签: javaspringspring-bootjackson

解决方案


我建议你在更高的层次上工作。

我想您的响应正在由 Web 服务序列化。也许您可以有一个实现发送带有@JsonExclude 的响应,而另一个不发送。

您可以使用 @Profile 注释启用所需的 Web 服务。

@RestController
@Profile("withExclude")
class WithExcludeController : IMyController {
  fun process() : ResponseWithExclude {
    // ...
  }
}

@RestController
@Profile("withoutExclude")
class WithoutExcludeController : IMyController {
  fun process() : ResponseWithoutExclude {
    // ...
  }
}

推荐阅读