使用 Spring 的表达式语言设置 @JsonProperty 名称(来自应用程序属性)

Set @JsonProperty name using Spring's Expression Language (from application properties)

假设我有一个 Foo class 这样的:

public class Foo {

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

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

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

您可以创建自定义 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());
        }

    }

}