在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的suggestion,我得到了这个通用的解决方案:
@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
配置为MethodInvokingFactoryBean
,返回单cacheManager
,以安全地调用其方法。
答案 0 :(得分:2)
如果你只是想确保在调用getter方法之前正确设置了cacheManager,那么你可以在配置级别上用
这样做。cacheManager(CacheManager) { ... }
pdfDocumentCache(MethodInvokingFactoryBean) { bean ->
bean.dependsOn = ['cacheManager']
targetClass = CacheManager
targetMethod = 'getROCache'
arguments = ['somecache']
}
pdfProcessor(PDFProcessor) {
documentCache = pdfDocumentCache
}
dependsOn
应确保在getROCache
bean初始化之前不调用静态cacheManager
方法。