Grails服务是用于在控制器之外实现业务逻辑(以及连接到支持服务/ DB等)的抽象。所以在典型的控制器中你可能有:
class DashboardController {
StatisticsService statsService
def index() {
// Fetches all the stats that need to be displayed to the
// admin on the dashboard.
AdminDashboardMetrics adm = statsService.getAdminStats()
render(view: "/dashboard", model: [ adm: adm ])
}
}
在这里,Grails会自动为DashboardController
注入一个StatisticsService
的bean实例(当然,前提是该服务是使用grails create-service ...
正确创建的)。
但是当我需要访问控制器外的StatisticsService
时会发生什么情况,特别是在 src/groovy
下?
// src/groovy/com/example/me/myapp/FizzBuzzer.groovy
class FizzBuzzer {
StatisticsService statsService
FizzBuzzer(StatisticsService statsService) {
super()
this.statsService = statsService
}
def doSomething(MyData input) {
MoreData result = statsService.calculate(input)
// use 'result' somehow, etc....
}
}
如何正确地将FizzBuzzer
广告与StatisticsService
传递给DashboardController
广告的UISearchbar
广告正确注入?
答案 0 :(得分:6)
您可以通过在conf> gt下的resources.groovy中定义注入登录来在spring bean中注入grails服务。弹簧
我在src / groovy中创建了一个ExampleService和Example类
ExampleService
class ExampleService {
def serviceMethod() {
println "do something"
}
}
src / groovy下的示例类
class Example {
ExampleService exampleService
def doSomething() {
def result = exampleService.serviceMethod()
}
}
在conf> spring 下的resources.groovy
beans = {
ex(Example){ bean ->
exampleService = ref('exampleService')
}
}
所以我可以在grails-app中将示例ex 定义为spring bean,它将自己注入ExampleService。
希望这会有所帮助。感谢
答案 1 :(得分:2)
您还可以使用grails.util.Holders
示例:
要注入MyService服务类,请使用Holders.applicationContext.getBean("myService")
其中“myService”是较低驼峰情况下服务类的名称。
答案 2 :(得分:0)
实现这一目标的一种方法是使用ServletContext-
ApplicationContext ctx = (ApplicationContext)ServletContextHolder.
getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
statisticsService = (StatisticsService ) ctx.getBean("statisticsService ")
请参阅此博客 - http://www.grailsbrains.com/availing-grails-goodies-in-srcjava-or-srcgroovy/