如何在非Wicket应用中实现类似Wicket的属性变量自动替换功能?
轻量属性变量替换实现方案
这里提供两种可直接落地的轻量实现方案,均符合Wicket同款${变量名}格式的替换需求:
方案1:使用Apache Commons Text的StringSubstitutor(开箱即用)
该工具属于Apache旗下专门处理字符串操作的轻量工具包,相比commons-configuration体积小、依赖少,功能完全匹配需求。
使用示例
Maven依赖引入:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.10.0</version> </dependency>
业务代码:
import org.apache.commons.text.StringSubstitutor; import java.util.Properties; import java.util.Map; // 加载配置文件 Properties props = new Properties(); props.load(YourClass.class.getResourceAsStream("/自定义配置文件路径.properties")); // 准备变量映射,可从模型对象、内存Map、业务上下文等任意来源取变量值 Map<String, Object> variables = Map.of( "currentTemperature", 24, "units", "℃" ); // 执行变量替换 StringSubstitutor substitutor = new StringSubstitutor(variables); String weatherMsg = substitutor.replace(props.getProperty("weather.message")); // 输出结果:Weather station reports that the temperature is 24 ℃ System.out.println(weatherMsg);
该工具还支持自定义占位符格式、变量不存在时的默认值配置、是否保留未匹配的原占位符等扩展能力,满足绝大多数业务场景。
方案2:纯JDK手写实现(零第三方依赖)
如果不想引入任何外部依赖,几十行正则代码就能实现基础替换能力:
import java.util.Properties; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; // 匹配${xxx}格式的变量占位符 private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\$\\{([^}]+)}"); public static String replaceVariables(String content, Map<String, Object> variables) { Matcher matcher = VARIABLE_PATTERN.matcher(content); StringBuffer result = new StringBuffer(); while (matcher.find()) { String varName = matcher.group(1); // 变量不存在时默认保留原占位符,可根据需求修改为抛异常、填默认值等逻辑 Object value = variables.getOrDefault(varName, matcher.group(0)); matcher.appendReplacement(result, Matcher.quoteReplacement(String.valueOf(value))); } matcher.appendTail(result); return result.toString(); } // 调用示例 public static void main(String[] args) throws Exception { Properties props = new Properties(); props.load(YourClass.class.getResourceAsStream("/自定义配置文件路径.properties")); Map<String, Object> variables = Map.of("currentTemperature", 24, "units", "℃"); String weatherMsg = replaceVariables(props.getProperty("weather.message"), variables); System.out.println(weatherMsg); }
如果需要支持嵌套变量、类型转换、EL表达式运算等进阶能力,在该基础上扩展即可,整体代码量极小。
内容的提问来源于stack exchange,提问作者magicmn
相关产品推荐
相关产品推荐

