Using Spring beans as a key with @Cacheable annotation

后端 未结 2 924
终归单人心
终归单人心 2021-01-03 16:45

How to make following to work: - a spring bean that has a method that should be cached with @Cacheable annotation - another spring bean that creates keys for the cache (Key

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 17:15

    I checked the underlying cache resolution implementation, there doesn't appear to be a simple way to inject in a BeanResolver which is required for resolving the beans and evaluating expressions like @beanname.method.

    So I would also recommend a somewhat hacky way along the lines of one which @micfra has recommended.

    Along what he has said, have a KeyCreatorBean along these lines, but internally delegate it to the keycreatorBean that you registered in your application:

    package pkg.beans;
    
    import org.springframework.stereotype.Repository;
    
    public class KeyCreatorBean  implements ApplicationContextAware{
        private static ApplicationContext aCtx;
        public void setApplicationContext(ApplicationContext aCtx){
            KeyCreatorBean.aCtx = aCtx;
        }
    
    
        public static Object createKey(Object target, Method method, Object... params) {
            //store the bean somewhere..showing it like this purely to demonstrate..
            return aCtx.getBean("keyCreatorBean").createKey(target, method, params);
        }
    
    }
    

提交回复
热议问题