一、前言
通过spring的spring-core包中的org.springframework.util.PropertyPlaceholderHelper、org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver类,将指定配置文件键值以自定义格式(如@{})的方式替换对于属性值,详情参见代码示例。
二、代码示例
1. PropertyPlaceholderHelperTest测试类
package test;@b@@b@import java.io.BufferedInputStream;@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.util.Properties;@b@import org.springframework.util.PropertyPlaceholderHelper;@b@import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;@b@@b@public class PropertyPlaceholderHelperTest {@b@ @b@ private static Properties properties = new Properties();@b@ @b@ private static PropertyPlaceholderHelper holder = new PropertyPlaceholderHelper("@{", "}");@b@ @b@ private static PlaceholderResolver resolver=new PlaceholderResolver() {@b@ @Override@b@ public String resolvePlaceholder(String placeholderName) {@b@ String value = properties.getProperty(placeholderName);@b@ return value;@b@ }@b@ };@b@ @b@ static{@b@ @b@ try {@b@ InputStream in = new BufferedInputStream(new FileInputStream(new File("C:\\www\\test123.properties")));@b@ properties.load(in);@b@ } catch (IOException e) {@b@ }@b@ @b@ }@b@ @b@ @b@@b@ public static void main(String[] args) {@b@ @b@ String kv = "@{keyname}:@{keyvalue}";@b@ @b@ System.out.println("替换前:========" + kv);@b@ @b@ String aa=holder.replacePlaceholders(kv, resolver);@b@ @b@ System.out.println("替换后:========" +aa );@b@ @b@ @b@ }@b@@b@}
2. test123.properties属性文件
keyname=website@b@keyvalue=www.xwood.net
3.控制台输出结果
替换前:========@{keyname}:@{keyvalue} @b@替换后:========website:www.xwood.net