Accessing Grails services from src/groovy

2019-02-25 11:54发布

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?

3条回答
【Aperson】
2楼-- · 2019-02-25 12:15

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.

查看更多
3楼-- · 2019-02-25 12:23

One way of achieving this is by using ServletContext-

ApplicationContext ctx = (ApplicationContext)ServletContextHolder.

getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)

statisticsService = (StatisticsService ) ctx.getBean("statisticsService ")

see this blog - http://www.grailsbrains.com/availing-grails-goodies-in-srcjava-or-srcgroovy/

查看更多
Fickle 薄情
4楼-- · 2019-02-25 12:26

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

查看更多
登录 后发表回答