Reputation: 11
Is it possible to inject Spring beans into a groovy script?
I want to be able to use service/repository methods from a spring application in groovy scripts
Upvotes: 0
Views: 550
Reputation: 27220
Is it possible to inject Spring beans into a groovy script?
Yes. You can "inject" any object you like, Spring Bean or otherwise, into a Groovy script. It isn't injection in the sense that Spring does dependency injection, but you can get the variable into the script easily by putting it in a shell binding:
def binding = new Binding()
// instead of "new"-ing up an instance, you could do this
// from wherever in your Spring app that you have injected
// the SomeHelper bean
binding.someHelper = new SomeHelper()
// script could be loaded from a file, or hardcoded,
// loaded from a db, etc...
def groovyScript = '''
println someHelper.magicNumber
'''
def shell = new GroovyShell(binding)
shell.evaluate(groovyScript)
Upvotes: 1