如何基于Spring Profile实现Kotlin类字段@JsonIgnore的条件生效控制
可行的实现方案有两种,分别是全局过滤器方案和字段级自定义过滤方案:
方案1:Jackson 过滤器 + Spring Profile 全局配置(推荐多字段场景使用)
该方案不需要修改原有数据类的业务逻辑,通过Spring不同环境配置不同的序列化规则即可实现需求。
- 先移除
version字段上的@JsonIgnore注解,给MyClass添加Jackson过滤器注解:
import com.fasterxml.jackson.annotation.JsonFilter @JsonFilter("myClassFilter") data class MyClass( val name: String, val version: Number )
- 编写Jackson自定义配置类,根据激活的Profile加载不同的序列化规则:
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider import com.fasterxml.jackson.module.kotlin.KotlinModule import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import org.springframework.http.converter.json.Jackson2ObjectMapperBuilderCustomizer @Configuration class JacksonProfileConfig { @Bean @Profile("live") fun liveJacksonCustomizer(): Jackson2ObjectMapperBuilderCustomizer { return Jackson2ObjectMapperBuilderCustomizer { builder -> builder.filters( SimpleFilterProvider().addFilter( "myClassFilter", SimpleBeanPropertyFilter.serializeAllExcept("version") ) ).modulesToInstall(KotlinModule.Builder().build()) } } @Bean @Profile("test") fun testJacksonCustomizer(): Jackson2ObjectMapperBuilderCustomizer { return Jackson2ObjectMapperBuilderCustomizer { builder -> builder.filters( SimpleFilterProvider().addFilter( "myClassFilter", SimpleBeanPropertyFilter.serializeAll() ) ).modulesToInstall(KotlinModule.Builder().build()) } } }
该方案不会覆盖Spring Boot默认的Jackson自动配置,其他全局序列化规则依然有效。
方案2:字段级自定义过滤(推荐单字段少量场景使用)
如果仅需要控制version一个字段的序列化,可以通过自定义属性过滤器实现,无需全局配置:
- 编写Spring上下文工具类,用于获取当前激活的环境:
import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.stereotype.Component @Component object EnvironmentContext : ApplicationContextAware { private lateinit var context: ApplicationContext override fun setApplicationContext(applicationContext: ApplicationContext) { context = applicationContext } fun isLiveProfile(): Boolean { return context.environment.activeProfiles.contains("live") } }
- 编写Jackson自定义属性过滤器,当处于
live环境时过滤该字段:
class LiveEnvironmentExcludeFilter { override fun equals(other: Any?): Boolean { // 返回true代表该字段值和过滤器值相等,会被@JsonInclude忽略 return EnvironmentContext.isLiveProfile() } override fun hashCode(): Int { return javaClass.hashCode() } }
- 给
version字段添加对应注解,移除原有的@JsonIgnore:
import com.fasterxml.jackson.annotation.JsonInclude data class MyClass( val name: String, @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = LiveEnvironmentExcludeFilter::class) val version: Number )
该方案对代码侵入更小,只需要修改对应字段的注解即可,不需要调整全局配置。
内容的提问来源于stack exchange,提问作者Joergi
相关产品推荐
相关产品推荐

