Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

dependency injection - How to inject Grails services into src/groovy classes

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...