在 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')}"
}
配置cacheDecorator
as MethodInvokingFactoryBean
,返回 singleton cacheManager
,以安全地调用其方法。