【发布时间】:2023-04-03 01:12:01
【问题描述】:
我需要你的快速帮助来解决一个小问题。
在我的一个项目中(使用 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 设置这个系统属性。
这里是代码
<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,因此缓存没有被禁用。当我在调试模式下运行应用程序并在应用程序上下文初始化后尝试获取System.getProperty("net.sf.ehcache.disabled") 时,它给了我正确的值。 (我尝试了真假)。
还有一件事我想提到我正在使用 spring 包装器来初始化我的缓存。
<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中实现吗?
【问题讨论】: