You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring 4.x升级至Spring 5.x:parseStringValue方法移除报错改造方案

Spring 4.x 升级至 Spring 5.x 解决 parseStringValue 方法移除问题

问题核心

Spring 5.x 中PropertyPlaceholderConfigurer已被标记为过时,且其内部的parseStringValue方法被移除,同时原代码的实现方式不符合Spring 5的最佳实践。以下是针对性的重构方案:

解决方案

放弃继承PropertyPlaceholderConfigurer的方式,改用Spring 5推荐的Environment组件管理属性,利用其自带的占位符解析能力替代parseStringValue,同时保持原有静态方法的兼容性。

方案1:缓存所有属性(兼容原有逻辑)

@Configuration
@PropertySource(name = "load", value = {"file:${propertyPath}/property.config"})
@Component
public class PropertiesUtil {
    private static Environment environment;
    private static Map<String, String> propertiesMap;

    @Autowired
    public void setEnvironment(Environment env) {
        environment = env;
        propertiesMap = new HashMap<>();
        // 遍历所有加载的属性源,解析并缓存属性
        MutablePropertySources propertySources = ((ConfigurableEnvironment) env).getPropertySources();
        propertySources.forEach(source -> {
            if (source instanceof EnumerablePropertySource) {
                EnumerablePropertySource<?> enumerableSource = (EnumerablePropertySource<?>) source;
                for (String key : enumerableSource.getPropertyNames()) {
                    String value = env.resolvePlaceholders(enumerableSource.getProperty(key).toString());
                    propertiesMap.put(key, value);
                }
            }
        });
    }

    public static String getProperty(String name) {
        return propertiesMap.get(name);
    }
}

方案2:实时解析属性(更高效,推荐)

无需提前缓存,调用时实时获取并解析占位符,避免缓存与实际配置不一致的问题:

@Configuration
@PropertySource(name = "load", value = {"file:${propertyPath}/property.config"})
@Component
public class PropertiesUtil {
    private static Environment environment;

    @Autowired
    public void setEnvironment(Environment env) {
        environment = env;
    }

    public static String getProperty(String name) {
        // 自动解析属性值中的嵌套占位符
        String rawValue = environment.getProperty(name);
        return rawValue != null ? environment.resolvePlaceholders(rawValue) : null;
    }
}

关键说明

  • @PropertySource中的${propertyPath}会被Spring自动解析,只要服务器环境中存在该属性(系统属性、环境变量或其他配置源均可)
  • Environment.resolvePlaceholders()方法完全替代原parseStringValue的功能,支持解析属性值中的嵌套占位符
  • 若要求占位符必须被解析(未解析则抛出异常),可改用environment.resolveRequiredPlaceholders()方法

内容的提问来源于stack exchange,提问作者Divya Bansal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:25:24