离开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());
}
}
然后当然您必须将其配置为 THECacheResolver
才能与@Configuration
that extends一起使用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);
}
}