0

I want to be able to include Services in my Groovy Classes in /src/groovy

I found a solution with :

myBean(MyBean) { bean ->        
    bean.autowire = 'byName'
}

But I dont want to make this entry in the resources.groovy for all Class, so is there a Solution to Autowire all classes in a specific folder?

I'm using grails 2.4.3

YAT
  • 456
  • 1
  • 4
  • 14

2 Answers2

1

This seems to be similar to this question: Grails 2.x service injection in Groovy/src

What we use and is proposed there is to get the service via the application context:

import grails.util.Holders
...
def myService = Holders.grailsApplication.mainContext.getBean 'myService'

It's not completely auto-wired, but seems to be the best way to get services into src/groovy.

Edit: also works for Grails 3

Community
  • 1
  • 1
1

You can make a class com.example.MyClass in src/groovy a Spring bean by adding the following to BuildConfig.groovy

grails.spring.bean.packages = ['com.example']

and annotating the class with @Component, e.g.

@Component
class MyClass {

    @Value('${conf.apiVersion}')
    String apiVersion

    @Autowired
    SomeService someService
}

As shown above, you can dependency-inject the class with the usual Spring annotations such as @Value and @Autowired. I find this a much more convenient way to register a Spring bean than modifying resources.groovy.

Dónal
  • 185,044
  • 174
  • 569
  • 824