我可以使用PropertyPlaceholderConfigurer在运行时在String上执行属性替换吗?

Ale*_*sky 1 spring ehcache

在Spring配置的一个区域中,我们使用:

applicationContext.xml:

<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" lazy-init="true">
    <property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

但是,ehcache.xml不是标准的spring bean配置文件,而是包含$ {ehcache.providerURL},我们要根据我们在其他地方使用PropertyPlaceHolderConfigurer配置的内容替换它们:

ehcache.xml:

<cacheManagerPeerProviderFactory
   ...
   providerURL=${ehcache.providerURL}
   ...
</cacheManagerPeerProviderFactory>
Run Code Online (Sandbox Code Playgroud)

我可以使用Maven/profile/filter组合,但这会创建一个特定于它正在构建的环境的构建.我真正想要做的是在运行时预处理ehcache.xml,根据PropertyPlaceHolderConfigurer读取的属性执行替换,然后将结果传递给EhCacheManagerBean.

此时,我正在考虑以某种方式复制@Value注释背后的功能,因为它可以替换"bla bla bla $ {property} bla bla bla",除非我需要在从磁盘读取文件后执行此操作.

关于如何解决这个问题的任何想法?

谢谢.-AP_

gbe*_*ley 6

要直接操作字符串,可以使用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);
Run Code Online (Sandbox Code Playgroud)

它使用相应的属性值替换模板中的值.