我有一个基于Spring的java应用程序,其中包含一些有用的组件.作为系统的一部分,我有一个groovy脚本,来处理一些报告.我想从groovy脚本中调用spring组件.
当我用Java编写时,我需要在@Component中使用@Autowired注释,即
@Component
class Reporter{
@Autowired
SearchService searchService;
void report(){
searchService.search(...);
...
}
}
我如何从groovy做同样的事情?
首先,我如何为整个脚本定义@Component?
以下代码:
@Component class Holder{
@Autowired
SearchService searchService;
def run(){
searchService.search("test");
}
}
new Holder().run()
在searchService上使用NPE失败.
如果重要的话,我正在使用从Java实例化的GroovyClassloader运行groovyscripts.
非常感谢提前!
解决方法:
如果您正在使用@Component,则应将Spring上下文创建为:
def ctx = new GenericApplicationContext()
new ClassPathBeanDefinitionScanner(ctx).scan('') // scan root package for components
ctx.refresh()
或者在XML中:
<context:component-scan base-package="org.example"/>
如果上面创建了上下文,您的代码应该有效.这是Groovy Codehaus的一个例子
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
@Component class CalcImpl3 {
@Autowired private AdderImpl adder
def doAdd(x, y) { adder.add(x, y) }
}
原文地址:https://codeday.me/bug/20190521/1147450.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。