@ConfigurationProperties绑定多点点分隔属性时整后缀作为Map键问题咨询
问题原因
Spring Boot的@ConfigurationProperties默认会将配置项中带.的key按分隔符拆分为嵌套Map结构,因此你直接通过完整属性名从properties中取值会返回null。
解决方案
方案1:框架内部自动展平嵌套Map(推荐,无侵入)
无需调整使用者的配置写法,只需要修改你的CustomEclipseLinkProperties类,新增嵌套Map展平逻辑即可,后续新增任何EclipseLink属性都自动支持,不需要额外调整代码:
import org.springframework.boot.context.properties.ConfigurationProperties; import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.Map; import java.util.LinkedHashMap; import org.eclipse.persistence.config.PersistenceUnitProperties; @ConfigurationProperties(prefix = "our.framework.eclipselink") public class CustomEclipseLinkProperties { private Map<String, Object> properties; private Map<String, Object> flattenedProperties; public Map<String, Object> getProperties() { return properties; } public void setProperties(Map<String, Object> properties) { this.properties = properties; } public String getBatchSize() { return (String) flattenedProperties.get(PersistenceUnitProperties.BATCH_WRITING_SIZE); } @PostConstruct public void initFlattenedProperties() { flattenedProperties = new HashMap<>(); flattenRecursive(properties, "", flattenedProperties); } private void flattenRecursive(Map<String, Object> source, String prefix, Map<String, Object> target) { if (source == null) return; for (Map.Entry<String, Object> entry : source.entrySet()) { String fullKey = prefix.isEmpty() ? entry.getKey() : prefix + "." + entry.getKey(); Object value = entry.getValue(); if (value instanceof LinkedHashMap) { flattenRecursive((Map<String, Object>) value, fullKey, target); } else { target.put(fullKey, value); } } } // 注入EntityManager时直接调用该方法获取所有属性即可 public Map<String, Object> getFinalEclipseLinkProperties() { return flattenedProperties; } }
方案2:调整配置写法
如果可以接受修改配置格式,直接在配置中把带.的属性名用方括号括起来,Spring就不会拆分key为嵌套结构:
our.framework.eclipselink.properties.[eclipselink.logging.level]=FINEST our.framework.eclipselink.properties.[eclipselink.logging.level.cache]=FINEST our.framework.eclipselink.properties.[eclipselink.logging.level.sql]=FINEST our.framework.eclipselink.properties.[eclipselink.logging.parameters]=true our.framework.eclipselink.properties.[eclipselink.jdbc.batch-writing.size]=1000 our.framework.eclipselink.properties.[eclipselink.jdbc.bind-parameters]=true our.framework.eclipselink.properties.[eclipselink.jdbc.batch-writing]=JDBC our.framework.eclipselink.properties.[eclipselink.jpa.uppercase-column-names]=false our.framework.eclipselink.properties.[eclipselink.jpa.uppercase-columns]=false
调整后原getBatchSize()方法不需要修改即可正常取到值。
内容的提问来源于stack exchange,提问作者payne
相关产品推荐
相关产品推荐

