2017-04-13 46 views
0

我想動態調用服務,以便服務名稱將作爲字符串值獲取,我們可以使用下面的代碼列出grails項目中的所有服務名稱。Grails:如何從字符串中調用服務和服務名稱

import org.codehaus.groovy.grails.plugins.metadata.GrailsPlugin 

for (type in ['service']) { 

    for (artifactClass in ctx.grailsApplication."${type}Classes") { 

     def clazz = artifactClass.clazz 

     def annotation = clazz.getAnnotation(GrailsPlugin) 
     if (annotation) { 
     println "$type $clazz.name from plugin '${annotation.name()}'" 
     } 
     else { 
     println "$type $clazz.name from application" 
     } 
    } 
} 

在這裏,我們將得到service.Is的artifactClass有任何選項可以使用此idea.Please幫我打電話給該服務。

回答

0

您可以從applicationContext

//inject application context bean 
def applicationContext 

//to use 
applicationContext."${yourServiceName}".serviceMethod() 
+0

得到該服務的豆添加到他的,如果你有'grailsApplication'已經,你就可以用'grailsApplication.mainContext'上下文。我更喜歡使用方法調用'getBean',而不是使用字符串插值,但這是個人而非功能:'grailsApplication.mainContext.getBean('yourServiceName')。serviceMethod()' – tylerwal

相關問題