1

在 Grails 2.3.7 上,服务公开了几个装饰器方法:

class CacheManager {
  static ReadOnlyCache getReadOnlyCache(name)
  static ReadWriteCache getReadWriteCache(name)
}

我想使用这些装饰器方法配置服务,如下所示:

beans = {
  cacheManager(CacheManager){ ... }

  pdfProcessor(PDFProcessor){
    documentCache = ref('cacheManager').getReadOnlyCache('docscache')
  }
  isbnValidator(ISBNValidator){
    cache = ref('cacheManager').getReadWriteCache('simplecache')
  }

有没有办法做到这一点?

更新

感谢 Ian 的建议,我得到了这个通用解决方案:

@Singleton
class CacheManager {
  static ReadOnlyCache getReadOnlyCache(name)
  static ReadWriteCache getReadWriteCache(name)
}

beans = {
  cacheManager(CacheManager){ bean ->
    bean.factoryMethod = 'getInstance'

  cacheDecorator(MethodInvokingFactoryBean) { bean ->
    bean.dependsOn = ['cacheManager']
    targetClass = CacheManager
    targetMethod = 'getInstance'      
  }

  pdfProcessor(PDFProcessor){
    documentCache = "#{cacheDecorator.getReadOnlyCache('docscache')}"
  }
  isbnValidator(ISBNValidator){
    cache = "#{cacheDecorator.getReadWriteCache('simplecache')}"
  }

配置cacheDecoratoras MethodInvokingFactoryBean,返回 singleton cacheManager,以安全地调用其方法。

4

1 回答 1

2

如果您只想确保在调用 getter 方法之前正确设置了 cacheManager,那么您可以纯粹在配置级别执行此操作,例如

cacheManager(CacheManager) { ... }

pdfDocumentCache(MethodInvokingFactoryBean) { bean ->
  bean.dependsOn = ['cacheManager']
  targetClass = CacheManager
  targetMethod = 'getROCache'
  arguments = ['somecache']
}

pdfProcessor(PDFProcessor) {
  documentCache = pdfDocumentCache
}

dependsOn应该确保在初始化beangetROCache之前不会调用静态方法。cacheManager

于 2014-06-22T11:09:35.643 回答