我需要你的快速帮助来解决一个小问题。
在我的一个项目中(使用 spring 作为核心容器),我使用 ehcache 来缓存数据。我正在使用 spring ehcache 注释项目 (http://code.google.com/p/ehcache-spring-annotations/)。
我希望能够根据外部属性灵活地启用和禁用 ehcache。我阅读了 ehcache 文档,发现它在内部读取系统属性 net.sf.ehcache.disabled,如果它设置为 true,缓存将被禁用,他们建议将其作为 -Dnet.sf.ehcache.disabled=true
在命令行中
我想通过外部化的 spring 属性文件来控制它。
然后我想到使用基于外部化属性的 MethodInvokingFactoryBean 在我的 spring 应用程序上下文文件中设置这个系统属性。
这是代码
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject">
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.System"/>
<property name="targetMethod" value="getProperties"/>
</bean>
</property>
<property name="targetMethod" value="putAll"/>
<property name="arguments">
<util:properties>
<prop key="net.sf.ehcache.disabled">"${ehcache.disabled}"</prop>
</util:properties>
</property>
</bean>
显然 ehcache.disabled
是通过我的外部属性文件控制的。
管道工程很好,但我想秩序没有到位。当应用程序上下文设置系统属性时,缓存已初始化,当缓存被初始化时没有属性 net.sf.ehcache.disabled
,因此缓存不会被禁用。当我在 Debug模式下运行应用程序并尝试在应用程序上下文初始化后获取 System.getProperty("net.sf.ehcache.disabled")
时,它给了我正确的值。 (我试过真假)。
还有一件事我想提一下,我正在使用 spring wrapper 来初始化我的缓存。
<ehcache:annotation-driven self-populating-cache-scope="method"/>
<ehcache:config cache-manager="cacheManager">
<ehcache:evict-expired-elements interval="20"/>
</ehcache:config>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:ehcache.xml"/>
我相信禁用缓存不会那么难。
我错过了什么?除了命令行之外,在 spring 中有什么简单的方法可以做到这一点吗?
最佳答案
从 Spring 3.1 开始,可以使用可以从外部属性读取属性的 bean 配置文件。您可以将声明的 bean 包装在 beans 元素中:
<beans profile="cache-enabled">
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:ehcache.xml"/>
</beans>
然后使用 this 中提到的外部属性激活它博文。
关于java - 如何在 spring 中使用外部属性禁用 ehcache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7293385/