Accessing Grails services from src/groovy

前端 未结 3 873
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 08:11

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 y

相关标签:
3条回答
  • 2021-01-21 08:40

    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/

    0 讨论(0)
  • 2021-01-21 09:01

    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

    0 讨论(0)
  • 2021-01-21 09:02

    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.

    0 讨论(0)
提交回复
热议问题