繁体   English   中英

将Spring Bean注入Groovy脚本

[英]Injecting Spring Beans to Groovy Script

我已经看到许多关于Groovy对象作为Spring Bean的示例,反之亦然。 我在Java EE应用程序中使用Groovy,如下所示:

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

这样,将使用Groovy编写的带有@Configurable批注的类注入Spring Bean。 现在还可以。

如何使用GroovyScriptEngine获得相同的GroovyScriptEngine 我不想定义一个类,而是希望它像普通脚本一样工作。 Spring / Groovy有能力做到这一点吗?

我已经看过有关此的帖子,但不确定是否能回答我的问题:

这里

您是说要向脚本中添加属性并注入这些属性吗? 您会提供吸气剂和吸气剂吗? 这对我来说没有多大意义。 有意义的是将mainContext添加到脚本的绑定中,或将选定的bean添加到绑定中。

然后,可以直接在脚本中访问这些bean(或上下文),就像注入了它们一样。

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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