V H
V H

Reputation: 8587

Grails: plugin injecting service into src groovy within a plugin

Apologies, since there are lots of links out there and I have tried a few examples including stuff that already works within my project(s) that are non plugin:

What I have tried:

Within my Plugin descriptor:

def doWithSpring = {
        someService(SomeService)
    }

Then within my end src/groovy

//def someService = Holders.grailsApplication.mainContext.getBean 'someService'
def someService

None of above works...

If I instantiate the service everything appears to work fine, I would prefer to inject it and its just taking a lot of time doing something rather basic :(

SomeService someService=new SomeService()

Any help would be appreciated

Not that I have ever seen it before (within a plugin) should I include conf/spring/resources.groovy and initialise bean in there ?

Upvotes: 0

Views: 755

Answers (2)

Burt Beckwith
Burt Beckwith

Reputation: 75671

In this case, like most cases, there's a way to access what you want without using holders. The Groovy class implements ServletContextListener, so there's a contextInitialized method with a ServletContextEvent event containing the ServletContext. So it wasn't necessary to use the ServletContextHolder to get the ServletContext - it was right there. You can see from the FAQ that the Spring ApplicationContext is stored in the ServletContext as an attribute. Once you have that, you can access whatever Spring beans you want; in this case the jenkinsService and the grailsApplication beans (you can get the config directly from the grailsApplication without using Holders for that.

I made these changes and did a bunch of cleanup, and sent a pull request.

Upvotes: 2

Ken
Ken

Reputation: 685

You can inject your service in a src/groovy class like so:

import com.example.SomeService
import grails.util.Holders

class SrcGroovy {

    SomeService someService = Holders.applicationContext.getBean("someService")

    // ...
}

Upvotes: 0

Related Questions