2012-04-06 75 views
1

在我们的Spring配置的一个方面,我们使用的是:我可以使用PropertyPlaceholderConfigurer在运行时执行String上的属性替换吗?

的applicationContext.xml

<bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" lazy-init="true"> 
    <property name="configLocation" value="classpath:ehcache.xml"/> 
</bean> 

然而,ehcache.xml中是不是一个标准的Spring bean配置文件,但包含$ {ehcache.providerURL }这是我们希望基于我们已经在其他地方PropertyPlaceHolderConfigurer配置成以置换:

ehcache.xml中

<cacheManagerPeerProviderFactory 
    ... 
    providerURL=${ehcache.providerURL} 
    ... 
</cacheManagerPeerProviderFactory> 

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

此时,我在考虑重复@Value注释背后的功能,因为它可以替换“bla bla bla $ {property} bla bla bla”,除非我需要在从磁盘读取文件后执行此操作。

关于如何去做这件事的任何想法?

谢谢。 -AP_

回答

2

经过一番搜索之前,做任何你想要使用XML做的,这里是我想出了本质。我将其打包到一个Factory中,该Factory接受一个资源并在用$ {propertyPlaceHolder}替换所有持有者的实际值的行后将其转换。

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注释中接受的东西。它也与PropertyPlaceholderConfigurer集成。

希望这可以帮助别人。

-AP_

1

PropertyPlaceholderConfigurer用于替换Spring配置文件中的属性。它不会替换外部文件中的属性。 PropertyPlaceholderConfigurer无法解决您的问题。

您可以覆盖org.springframework.cache.ehcache.EhCacheManagerFactoryBean.afterPropertiesSet()方法和创造CacheManager.You知道如何清洁可:)

+0

Spring中有一些代码需要使用@Value(“bla $ {param} bla)并正确地进行替换。我想在运行时以某种方式使用此代码作为字符串传递我的文件内容,并取回参数替换的字符串。 – 2012-04-06 01:16:35

+2

经过一番挖掘,我发现这个: ((ConfigurableApplicationContext)applicationContext).getBeanFactory()。resolveEmbeddedValue(“$ {someValue}”); 我可以读取任何旧文件,然后使用此方法解析所有占位符。 Spring中有什么可以让我在不需要编写更多代码的情况下从bean配置中做到这一点? – 2012-04-06 02:33:14

+0

我认为阿迪的答案是一个相当不错的破解。将XML读取到字符串中,对所需的部分进行字符串替换,将字符串设置为配置位置(InputStreamResource/StringBufferInputStream),然后调用super。 – sourcedelica 2012-04-06 14:45:57

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); 

它与相应的属性值模板替换值。

相关问题