如何将Grails服务注入到src / groovy类中 [英] How to inject Grails services into src/groovy classes
问题描述
grails create-service com.example.Widget
创建一个Grails服务,那么我该如何将该服务的引用(一个bean)注入类 src / groovy
? 实际上Grails官方文档中并没有解释这一点,而广泛的搜索转向nadda 。
1)您可以使用Spring Beans将服务注入非artefact常规文件,使用 resources.groovy
:
MyClass.groovy
class MyClass {
def widgetService
...
}
resources.groovy
beans = {
myclass(com.example.MyClass){
widgetService = ref('widgetService')
}
}
$ c $ 2> 还有一个额外的 @Autowired
注释那可以做t同样的事情:
MyClass.groovy
import org.springframework.beans.factory.annotation.Autowired
class MyClass {
@Autowired
def widget
...
}
resources.groovy
beans = {
myclass(com.example.MyClass){}
}
$ p注意 - 这次 myclass
bean不需要对小部件的引用 / code>。
3)有一种替代方法来注入 WidgetService
- 使用 Holders
类来获取 grailsApplication
,它将引用现有的bean。
import grails.util.Holders
$ b $ class MyClass {
def widgetService = Holders.grailsApplication.mainContext .getBean('widgetService')
...
}
**更新**
4) 1)和2)的混合体 -
在 resources.groovy 中拥有由 autowire = true
注入的bean: p>
MyClass.groovy
class MyClass {
def widgetService
...
}
resources.groovy
beans = {
myclass(com.example.MyClass){bean - > ;
bean.autowire = true
}
}
这是我一直在本地使用的方法,因为我觉得它是最干净的,但它确实更多地利用了Grail的魔术(好或坏)。
Grails 2.4.x here. If I created a Grails service using grails create-service com.example.Widget
, then how can I inject a reference of that service (a "bean") into a class under src/groovy
?
This is actually not explained anywhere in the official Grails docs, and extensive searching turned back nadda.
解决方案 1) You can use Spring Beans to inject a service into a non-artefact groovy file, using resources.groovy
:
MyClass.groovy
class MyClass {
def widgetService
...
}
resources.groovy
beans = {
myclass(com.example.MyClass) {
widgetService = ref('widgetService')
}
}
2) There is also an additional @Autowired
annotation that can do the same thing:
MyClass.groovy
import org.springframework.beans.factory.annotation.Autowired
class MyClass {
@Autowired
def widget
...
}
resources.groovy
beans = {
myclass(com.example.MyClass) {}
}
Notice - this time the myclass
bean doesn't need the reference to the widget
.
3) There is an alternative to injecting the WidgetService
- using the Holders
class to get the grailsApplication
which will have a reference to the existing bean.
import grails.util.Holders
class MyClass {
def widgetService = Holders.grailsApplication.mainContext.getBean('widgetService')
...
}
**Update**
4) There is another option that is a hybrid of 1) and 2) -
Having the bean(s) injected by autowire=true
within resources.groovy:
MyClass.groovy
class MyClass {
def widgetService
...
}
resources.groovy
beans = {
myclass(com.example.MyClass) { bean ->
bean.autowire = true
}
}
This is the approach I've been using locally as I feel it's the cleanest, but it does take more advantage of Grail's 'magic' (for better or worse).
这篇关于如何将Grails服务注入到src / groovy类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!