Dav*_*hao 7 java spring caching dependency-injection
我们使用 Spring 缓存框架进行缓存,并且我们希望能够支持多个缓存命名空间,例如“book”或“isbn”,缓存命名空间是可配置的,而不是在类中进行硬编码,例如具有
@Cacheable({ "book","isbn"})
public Book findBook(ISBN isbn) {...}
Run Code Online (Sandbox Code Playgroud)
我们希望能够以某种方式从属性文件中注入缓存名称,以便可以动态设置缓存名称,例如:
@Cacheable({ #cachename1, #cachename2})
public Book findBook(ISBN isbn) {...}
Run Code Online (Sandbox Code Playgroud)
我在这里使用 SpEL,但不知道这是否可行。
小智 6
离开smartwjw的回答......
我希望通过 spring 环境变量解析 cacheNames,例如@Cacheable("${my.config.property.name}"). 我通过自定义完成了这个CacheResolver
import java.util.Collection;
import java.util.stream.Collectors;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
import org.springframework.cache.interceptor.SimpleCacheResolver;
import org.springframework.core.env.PropertyResolver;
public class PropertyResolvingCacheResolver
extends SimpleCacheResolver {
private final PropertyResolver propertyResolver;
protected PropertyResolvingCacheResolver(CacheManager cacheManager, PropertyResolver propertyResolver) {
super(cacheManager);
this.propertyResolver = propertyResolver;
}
@Override
protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) {
Collection<String> unresolvedCacheNames = super.getCacheNames(context);
return unresolvedCacheNames.stream()
.map(unresolvedCacheName -> propertyResolver.resolveRequiredPlaceholders(unresolvedCacheName)).collect(Collectors.toList());
}
}
Run Code Online (Sandbox Code Playgroud)
当然,您必须将其配置为 THECacheResolver才能与@Configuration扩展名一起使用org.springframework.cache.annotation.CachingConfigurerSupport。
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
public static final String PROPERTY_RESOLVING_CACHE_RESOLVER_BEAN_NAME = "propertyResolvingCacheResolver";
@Autowired
private CacheManager cacheManager;
@Autowired
private Environment springEnv;
@Bean(PROPERTY_RESOLVING_CACHE_RESOLVER_BEAN_NAME)
@Override
public CacheResolver cacheResolver() {
return new PropertyResolvingCacheResolver(cacheManager, springEnv);
}
}
Run Code Online (Sandbox Code Playgroud)
value不可以, @Cacheable 注释的缓存名称 ( ) 属性不支持动态(SpEL 或其他)表达式。您必须实现您自己的版本org.springframework.cache.annotation.SpringCacheAnnotationParser并将其注入到框架中。
| 归档时间: |
|
| 查看次数: |
10624 次 |
| 最近记录: |