Spring 占位符机制非常干净和强大,不幸的是它仅适用于 Spring 文件。
我正在使用 EhCahe,并且我想在 ehcache.xml
文件上使用占位符机制。我有自己的 EhCache 工厂 bean,我可以将此库配置作为 InputStream。因此,为了实现我的目标,我需要做的就是:
- 从类路径读取xml文件内容
- 访问当前 spring.xml 文件的属性占位符(配置了我的 bean 的文件)
- 调用读取资源上的占位符
- 将资源作为输入流返回给库
所以我的问题是,如何做到这一点,在 Spring 允许的情况下尽可能紧凑?我想避免创建占位符本身,因此代码将尽可能少地发挥“魔力”,因此我想使用 xml 文件中的属性配置。
最佳答案
EhCache 支持 ehcache.xml 文件中的系统属性占位符替换,因此一种选择是将 Spring 占位符值复制到系统属性,以便可以在 ehcache.xml 文件中引用它们:
在 spring 上下文 xml 中...
<!-- Copy Spring placeholder value to System props -->
<bean id="systemProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" value="#{@systemProperties}" />
<property name="targetMethod" value="putAll" />
<property name="arguments">
<util:properties>
<prop key="cache.ttl">${cache.ttl}</prop>
</util:properties>
</property>
</bean>
然后在您的 ehcache.xml 文件中,您现在可以使用上面填充的 ${cache.ttl}
占位符:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<cache name="myCache" timeToLiveSeconds="${cache.ttl}" maxElementsInMemory="1000" overflowToDisk="false" />
</ehcache>
关于java - 如何在java代码中调用Spring资源上的当前属性占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14772224/