简体   繁体   中英

Injecting Spring Beans to Groovy Script

I've seen many examples about Groovy objects as Spring beans but not vice versa. I'm using Groovy in a Java EE application like this:

GroovyCodeSource groovyCodeSource = new GroovyCodeSource(urlResource);
Class groovyClass = loader.parseClass(groovyCodeSource, false);
return (GroovyObject) groovyClass.newInstance();

In this way, classes written in Groovy with @Configurable annotation are being injected with Spring beans. It's OK for now.

How can I get the same by using GroovyScriptEngine ? I don't want to define a class and I want it to work like a plain script. Is Spring/Groovy capable of that?

I've seen a post about this but I'm not sure whether it answers my question or not:

HERE

Do you mean that you'd like to add properties to the script, and inject those? Would you provide getter and setter? This does not make much sense to me. What makes sense, is adding the mainContext to the bindings of the script, or adding selected beans to the bindings.

These beans - or the context - would then be accessible directly in the script, as if it was injected.

def ctx = grailsApplication.mainContext
def binding = new Binding([:])
Map variables = [
        'aService',
        'anotherService'
].inject([config:grailsApplication.config, mainContext:ctx]) { m, beanName ->
    def bean = ctx.getBean(beanName)
    m[beanName] = bean
    m
}
binding.variables << variables

def compiler = new CompilerConfiguration()
compiler.setScriptBaseClass(baseScriptClassName)
def shell = new GroovyShell(new GroovyClassLoader(), binding, compiler)
script=shell.parse(scriptStr)
script.binding=binding


script.init()
script.run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM