且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 Grails 服务注入 src/groovy 类

更新时间:2023-09-21 09:27:28

1) 您可以使用 Spring Beans 将服务注入到非人工制品的 groovy 文件中,使用 resources.groovy代码>:

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) 还有一个额外的 @Autowired 注释可以做同样的事情:

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) {}
}

注意 - 这次 myclass bean 不需要对 widget 的引用.

Notice - this time the myclass bean doesn't need the reference to the widget.

3) 注入 WidgetService 的替代方法 - 使用 Holders 类来获取 grailsApplication它将引用现有的 bean.

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')

    ...
}

**更新**

4) 还有另一种选择是 1) 和 2) 的混合 -让 autowire=trueresources.groovy 中注入 bean:

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
    }
}

这是我一直在本地使用的方法,因为我觉得它是最干净的,但它确实更多地利用了 Grail 的魔法"(无论好坏).

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).