Spring bean initialization depends on a different number of beans

In my Spring / Grails / Groovy app, I configure the beans cache:

rulesCache(InMemoryCache){..}
countriesCache(InMemoryCache){..}

myService(ServiceBean){
  cache = ref('rulesCache')
}

The cache manager provides specialized services when retrieving caches, so I provide the manager with a list of beans caches:

cacheMgr(CacheManager){
  caches = [ ref('rulesCache'), ref('countriesCache')]
}

Services should get the beans cache from the manager, they cannot be "connected to the network" (the manager returns the cache delegate, not the cache itself, why), so I circumvented this problem by doing:

  cacheMgr(CacheManager){
    caches = [ ref('rulesCache'), ref('countriesCache')]
  }

  cacheMgrDelegate(MethodInvokingFactoryBean) { bean ->
      bean.dependsOn = ['cacheMgr']
      targetObject = cacheMgr
      targetMethod = 'getManager'
   }

   myService(SomeService){
     cache = "#{cacheMgrDelegate.getCache('rulesCache')}"
   }

This works fine, but the beans cache is arbitrary, so I cannot provide a list to the manager. I managed to get around this problem by listening to message initialization events from objects like cache and registering each cache manually using the manager:

CacheManager implements BeanPostProcessor {
    postProcessAfterInitialization(bean, beanName){
      if(bean instanceof ICache)
         registerCache(bean)
      return bean
    }
}

Problem

, Spring myService cacheManager beans, getCache() null:

myService(SomeService){
   cache = "#{cacheMgrDelegate.getCache('rulesCache')}"
}

, . dependsOn, beans , .

Spring CacheManager.getCache(name) "" - , :

getCache(String name){
  CacheProxy proxy = createProxy()
  proxies.add(proxy)
  return proxy
}

beans cacheManager :

onApplicationContext(){
   proxies.each{ proxy ->
     completeInit(proxy)
   }
}

? : -)

+4
1

ICache ? CacheManager :

CacheManager {
    @Autowired
    public void setCaches(List<ICache> caches) {
        ...
    }
    ...
}
+3

All Articles