我的spring项目有基于java的JPA配置:
@Configuration
@EnableJpaRepositories(basePackageClasses = {PackageMarker.class})
@EnableTransactionManagement(proxyTargetClass = true)
@EnableCaching
public class FooJPAConfig implements CachingConfigurer {
@Bean
@Override
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("default")));
return cacheManager;
}
@Bean
@Override
public KeyGenerator keyGenerator() {
return new DefaultKeyGenerator();
}
//...
}
如何告诉spring使用特定的ehcache.xml
文件?
答案 0 :(得分:2)
您需要更改cacheManager
才能集成EhCache。您当前的代码不会让EhCache进入图片。
配置看起来像
@Configuration
@EnableJpaRepositories(basePackageClasses = {PackageMarker.class})
@EnableTransactionManagement(proxyTargetClass = true)
@EnableCaching
public class FooJPAConfig implements CachingConfigurer {
@Bean
public EhCacheManagerFactoryBean cacheFactoryBean() {
EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("whatever-name.xml")); //this is where you set the location of the eh-cache configuration file
return ehCacheManagerFactoryBean;
}
@Bean
@Override
public CacheManager cacheManager() {
EhCacheCacheManager cacheManager = new EhCacheCacheManager();
cacheManager.setCacheManager(cacheFactoryBean().getObject());
return cacheManager;
}
@Bean
@Override
public KeyGenerator keyGenerator() {
return new DefaultKeyGenerator();
}
}
您还必须将spring-context-support
作为对类路径的依赖(适用于Spring 3.2)
请注意,上面的代码激活了Spring -EhCache集成,而不是JPA-EhCache集成。这意味着你可以在实体上使用Spring的@Cacheable
而不是EhCache的@Cache
。
答案 1 :(得分:0)
毕竟我可以通过将此代码添加到配置类来解决问题:
protected static final String EHCACHE_CONFIGURATIONRESOURCENAME_PROPERTY = "net.sf.ehcache.configurationResourceName";
@Bean(name = BEAN_ENTITY_MANAGER_FACTORY)
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = createLocalContainerEntityManagerFactoryBean();
// ...
processOptionalProperty(EHCACHE_CONFIGURATIONRESOURCENAME_PROPERTY, em);
return em.getObject();
}
protected void processOptionalProperty(String propertyName, LocalContainerEntityManagerFactoryBean em) {
String value = "";// read propertyName from configuration file
setPropertyValue(propertyName, em, value);
}
protected void setPropertyValue(String propertyName, LocalContainerEntityManagerFactoryBean em, Object value) {
if (value != null) {
Map<String, Object> jpaPropertyMap = em.getJpaPropertyMap();
jpaPropertyMap.put(propertyName, value);
em.setJpaPropertyMap(jpaPropertyMap);
}
}