【问题标题】:Set @JsonProperty name using Spring's Expression Language (from application properties)使用 Spring 的表达式语言设置 @JsonProperty 名称(来自应用程序属性)
【发布时间】:2021-07-02 13:53:57
【问题描述】:

假设我有一个像这样的Foo 类:

public class Foo {

    @JsonProperty("${PROPERTY_NAME_FROM_APP_PROPERTIES}")
    private String foo;
    
}

我们如何使用SpEL 实现动态 JSON 属性名称?

【问题讨论】:

    标签: java spring jackson spring-el


    【解决方案1】:

    您可以创建自定义JacksonAnnotationIntrospector 并覆盖Spring 的默认ObjectMapper

    @Configuration
    public class JacksonConfig {
    
        @Bean
        @Primary
        public ObjectMapper objectMapper(Environment environment) {
            ObjectMapper mapper = new ObjectMapper();
    
            mapper.setAnnotationIntrospector(new ExpressionLanguageJacksonAnnotationIntrospector(environment));
    
            return mapper;
        }
    
        public static class ExpressionLanguageJacksonAnnotationIntrospector extends JacksonAnnotationIntrospector {
    
            private final Environment environment;
            
            public ExpressionLanguageJacksonAnnotationIntrospector(Environment environment) {
                this.environment = environment;
            }
    
            @Override
            public PropertyName findNameForSerialization(Annotated annotated) {
                PropertyName name = super.findNameForSerialization(annotated);
    
                if (name == null) {
                    return null;
                }
    
                return PropertyName.construct(environment.resolvePlaceholders(name.getSimpleName()), name.getNamespace());
            }
    
        }
    
    }
    

    【讨论】:

    • 这很危险,因为它会忽略任何其他 ObjectMapper 自定义,这在 Spring Boot 应用程序中可能很多。最好实现一个返回Jackson2ObjectMapperBuilderCustomizer@Bean 方法并自定义构建器,而不是覆盖整个ObjectMapper
    【解决方案2】:

    你不能;注释由 Jackson 处理,而不是 Spring。

    【讨论】:

    • 不过,我可以修改 Spring 使用的 Jackson 的 ObjectMapper 以添加自定义 JacksonAnnotationIntrospector 来获取这些应用程序属性,对吧?
    • 我认为是的,是的,所以您似乎已经有了答案——那么真正的问题是什么?
    • 我在发布问题后立即找到了答案。
    猜你喜欢
    • 2018-04-03
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 2012-03-30
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多