spring cache 5: ProxyCachingConfiguration
当注解 @EnableCaching 对一个类进行修饰时,就会生成一些bean
这个类很简单
/**
* {@code @Configuration} class that registers the Spring infrastructure beans necessary
* to enable proxy-based annotation-driven cache management.
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
* @see EnableCaching
* @see CachingConfigurationSelector
*/
@Configuration
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class ProxyCachingConfiguration extends AbstractCachingConfiguration {
@Bean(name = CacheManagementConfigUtils.CACHE_ADVISOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public BeanFactoryCacheOperationSourceAdvisor cacheAdvisor() {
BeanFactoryCacheOperationSourceAdvisor advisor = new BeanFactoryCacheOperationSourceAdvisor();
advisor.setCacheOperationSource(cacheOperationSource());
advisor.setAdvice(cacheInterceptor());
if (this.enableCaching != null) {
advisor.setOrder(this.enableCaching.<Integer>getNumber("order"));
}
return advisor;
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public CacheOperationSource cacheOperationSource() {
return new AnnotationCacheOperationSource();
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public CacheInterceptor cacheInterceptor() {
CacheInterceptor interceptor = new CacheInterceptor();
interceptor.configure(this.errorHandler, this.keyGenerator, this.cacheResolver, this.cacheManager);
interceptor.setCacheOperationSource(cacheOperationSource());
return interceptor;
}
}
第3个方法定义了 cache Interceptor,表示当有cache相关注解时,真正执行的是 CacheInterceptor.invoke 方法
第2个方法定义了 AnnotationCacheOperationSource,这是一个全局的类,在启动过程中就会对被cache相关注解修饰的方法进行缓存,缓存在AbstractFallbackCacheOperationSource.attributeCache 属性中。可以看到spring 虽然用了反射,但内部用了很多这种local cache的方式,避免每次都需要计算一边
第1个方法定义了一个BeanFactoryCacheOperationSourceAdvisor,它的作用是在启动过程中对每个被缓存修饰的类构造时,计算Interceptor链,后面具体分析