Spring context属性 - placholder ehcahe配置

Den*_*s S 7 java spring ehcache

我有一个spring context xml文件

<context:property-placeholder location="classpath:cacheConfig.properties"/>

<bean id="cacheManager"
    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="cacheManagerName" value="cacheName"/>
    <property name="shared" value="false"/>
    <property name="configLocation" value="classpath:cacheConfig.xml"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

目标是允许客户编辑属性文件,如下所示

cache.maxMemoryElements="2000"
Run Code Online (Sandbox Code Playgroud)

然后在实际的cacheConfig.xml文件中有这个

<cache name="someCacheName"
   maxElementsInMemory="${cache.maxMemoryElements}" ... />
Run Code Online (Sandbox Code Playgroud)

这样我们不希望客户改变的项目不会暴露.当然,上述细节仅部分详细,不起作用.目前我在日志文件中看到了这一点

Invocation of init method failed; nested exception is net.sf.ehcache.CacheException: Error configuring from input stream. Initial cause was null:149: Could not set attribute "maxElementsInMemory".
Run Code Online (Sandbox Code Playgroud)

提前致谢...

ska*_*man 12

您的示例用于EhCacheManagerFactoryBean公开CacheManager对外部cacheConfig.xml文件中定义的缓存的引用.正如@ ChssPly76指出的那样,Spring的属性解析器只能在Spring自己的bean定义文件中运行.

但是,您不必在外部文件中定义单个高速缓存,您可以在Spring bean定义文件中定义它们,使用EhCacheFactoryBean:

FactoryBean,用于创建命名的EHCache Cache实例...如果未在缓存配置描述符中配置指定的命名缓存,则此FactoryBean将使用提供的名称和指定的缓存属性构造Cache的实例,并将其添加到CacheManager中后来检索.

换句话说,如果您使用EhCacheFactoryBean引用尚未定义的命名高速缓存cacheConfig.xml,则Spring将创建并配置新的高速缓存实例并CacheManager在运行时注册它.这包括指定类似的东西maxElementsInMemory,因为这将在Spring bean定义文件中指定,您将完全支持属性解析器:

<context:property-placeholder location="classpath:cacheConfig.properties"/>

<bean id="myCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
    <property name="cacheManager" ref="cacheManager"/>
    <property name="maxElementsInMemory" value="${cache.maxMemoryElements}"/>
</bean>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="shared" value="false"/>
    <property name="configLocation" value="classpath:cacheConfig.xml"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

  • 如果要配置非缓存的内容,该怎么办?例如,cacheManagerPeerListenerFactory的属性? (3认同)