Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Grails services from src/groovy

Grails services are abstractions used for implementing business logic (as well as connecting to backing services/DBs, etc.) outside of a controller. So in a typical controller you might have:

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

Here, Grails automatically injects the DashboardController with a bean instance of StatisticsService (provided of course that the service was properly created with grails create-service ...).

But what happens when I need to access StatisticsService outside of a controller, and particularly, under 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....
    }
}

How do I properly inject FizzBuzzer with the same StatisticsService instance ad what is passed into DashboardController?

like image 478
smeeb Avatar asked Jan 07 '23 07:01

smeeb


2 Answers

You can inject grails service in spring bean by defining injection login in resources.groovy under conf > spring

As I made an ExampleService and Example class in src/groovy

ExampleService

class ExampleService {

 def serviceMethod() {
    println "do something"
 }

}

Example Class under src/groovy

class Example {

ExampleService exampleService

 def doSomething() {
    def result = exampleService.serviceMethod()
 }
}

resources.groovy under conf>spring

beans = {

 ex(Example){ bean ->
    exampleService = ref('exampleService')
 }
}

so I can define Example ex as spring bean in grails-app and it will have ExampleService injected by itself.

Hope this helps. Thanks

like image 149
Anshul Avatar answered Feb 16 '23 09:02

Anshul


You can also get a service using grails.util.Holders

Example:

For injecting MyService service class, use Holders.applicationContext.getBean("myService")

Where "myService" is the name of your service class in lower camel case.

like image 31
s3c3t3 Avatar answered Feb 16 '23 11:02

s3c3t3