Spring 我可以使用PropertyPlaceHolderConfigure在运行时替换字符串上的属性吗?
在Spring配置的一个方面,我们正在使用: applicationContext.xml:Spring 我可以使用PropertyPlaceHolderConfigure在运行时替换字符串上的属性吗?,spring,ehcache,Spring,Ehcache,在Spring配置的一个方面,我们正在使用: applicationContext.xml: 但是,ehcache.xml不是标准的Springbean配置文件,而是包含${ehcache.providerURL},我们希望根据在别处使用PropertyPlaceHolderConfigure配置的内容来替换它: ehcache.xml: PropertyPlaceHolderConfigure用于替换Spring配置文件中的属性。它不会替换外部文件中的属性。无法使用PropertyPlac
但是,ehcache.xml不是标准的Springbean配置文件,而是包含${ehcache.providerURL},我们希望根据在别处使用PropertyPlaceHolderConfigure配置的内容来替换它:
ehcache.xml:
PropertyPlaceHolderConfigure用于替换Spring配置文件中的属性。它不会替换外部文件中的属性。无法使用PropertyPlaceHolderConfiguration解决您的问题
您可以重写org.springframework.cache.ehcache.EhCacheManagerFactoryBean.afterPropertiesSet()方法,并在创建CacheManager之前对xml执行任何操作。您知道它有多干净:)经过一些搜索,下面是我想到的要点。我将其打包到一个工厂中,该工厂接受一个资源,并在用${propertyPlaceHolder}替换所有行后将其转换为holder的实际值
final ConfigurableListableBeanFactory
factory =
((ConfigurableApplicationContext) applicationContext).getBeanFactory();
String line = null;
while ((line = reader.readLine()) != null) {
try {
final String
result = factory.resolveEmbeddedValue(line);
writer.println(result);
}
catch (final Exception e) {
log.error("Exception received while processing: " + line, e);
throw e;
}
}
此解决方案的好处在于,它使用的工具与Spring解析@Value(“${fooBar}”)注释时使用的工具相同。这意味着您可以使用SpEL和Spring在@Value注释中通常接受的其他任何内容。它还与PropertyPlaceHolderConfigure集成
希望这对别人有帮助
-要直接操作字符串,可以使用org.springframework.util.PropertyPlaceholderHelper
String template = "Key : ${key} value: ${value} "
PropertyPlaceholderHelper h = new PropertyPlaceholderHelper("${","}");
Properties p = new Properties();
p.setProperty("key","mykey");
p.setProperty("value","myvalue");
String out = h.replacePlaceholders(template,p);
它用相应的特性值替换模板中的值 Spring中有一些代码接受@Value(“bla${param}bla)并正确地进行替换。我想在运行时以某种方式使用此代码将文件的内容作为字符串传递,然后返回一个替换了参数的字符串。经过一番挖掘后,我发现:((ConfigurableApplicationContext)applicationContext).getBeanFactory().resolveEmbeddedValue(“${someValue}”);我可以读取任何旧文件,然后使用此方法解析所有占位符。Spring中是否有任何东西允许我从bean配置中执行此操作,而无需编写更多代码?我认为Adi的答案是一个相当不错的破解。将XML读入字符串,对所需部分进行字符串替换,将字符串设置为配置位置(InputStreamResource/StringBufferInputStream),然后调用super.Adi,如果我不能成功地使用更通用的方法来筛选${propertyPlaceHolders}的任意文件,我肯定会使用您的解决方案.事实证明,我发现了另一个配置hibernate二级缓存的案例,因此我需要一个更通用的解决方案。
final ConfigurableListableBeanFactory
factory =
((ConfigurableApplicationContext) applicationContext).getBeanFactory();
String line = null;
while ((line = reader.readLine()) != null) {
try {
final String
result = factory.resolveEmbeddedValue(line);
writer.println(result);
}
catch (final Exception e) {
log.error("Exception received while processing: " + line, e);
throw e;
}
}
String template = "Key : ${key} value: ${value} "
PropertyPlaceholderHelper h = new PropertyPlaceholderHelper("${","}");
Properties p = new Properties();
p.setProperty("key","mykey");
p.setProperty("value","myvalue");
String out = h.replacePlaceholders(template,p);