我需要你的快速帮助来解决一个小问题。
在我的一个项目(使用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
,因此缓存不会被禁用。当我在调试模式下运行应用程序并尝试在应用程序上下文初始化后获得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>
然后像这篇博文中提到的那样使用一个外部属性来激活它
最简单的方法(spring 3.1之前)是在MethodInvokingFactoryBean声明中添加一个bean id,然后添加一个依赖关系。
如果外部属性不为真,可以返回NoOpCacheManager
对象
@Value("${cache.enabled}")
private Boolean cacheEnabled;
@Bean(destroyMethod="shutdown")
public net.sf.ehcache.CacheManager ehCacheManager() {
net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
CacheConfiguration cacheConfiguration = new CacheConfiguration();
cacheConfiguration.setName("mycache");
cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");
cacheConfiguration.setMaxEntriesLocalHeap(1000);
cacheConfiguration.setTimeToIdleSeconds(0);
cacheConfiguration.setTimeToLiveSeconds(3600);
cacheConfiguration.persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE));
config.addCache(cacheConfiguration);
cacheMaxEntriesLocalHeap, cacheEvictionPolicy);
return net.sf.ehcache.CacheManager.newInstance(config);
}
@Bean
@Override
public CacheManager cacheManager() {
if(cacheEnabled) {
log.info("Cache is enabled");
return new EhCacheCacheManager(ehCacheManager());
}else{
log.info("Cache is disabled");
return new NoOpCacheManager();
}
}