tmp*_*210 5 java groovy spring autowired
我有一个基于Spring的java应用程序,其中包含一些有用的组件.作为系统的一部分,我有一个groovy脚本,来处理一些报告.我想从groovy脚本中调用spring组件.当我用Java编写时,我需要在其中使用@Autowired注释@Component,即
@Component
class Reporter{
@Autowired
SearchService searchService;
void report(){
searchService.search(...);
...
}
}
Run Code Online (Sandbox Code Playgroud)
我如何从groovy做同样的事情?首先,我如何定义@Component整个脚本?以下代码:
@Component class Holder{
@Autowired
SearchService searchService;
def run(){
searchService.search("test");
}
}
new Holder().run()
Run Code Online (Sandbox Code Playgroud)
在NPE上失败了searchService.GroovyClassloader如果重要的话,我正在运行使用Java实例化的groovyscripts .非常感谢提前!
如果您使用@Component,您应该创建 Spring 上下文:
def ctx = new GenericApplicationContext()
new ClassPathBeanDefinitionScanner(ctx).scan('') // scan root package for components
ctx.refresh()
Run Code Online (Sandbox Code Playgroud)
或在 XML 中:
<context:component-scan base-package="org.example"/>
Run Code Online (Sandbox Code Playgroud)
如果按上述方式创建上下文,您的代码应该可以工作。这是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) }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6931 次 |
| 最近记录: |