I have a spring-based java application with some useful components. As a part of the system I have a groovy script, to process some reports. I would like to call a spring component from groovy script.
When I'm writing in Java, I need to use @Autowired
annotation inside the @Component
, i.e.
@Component
class Reporter{
@Autowired
SearchService searchService;
void report(){
searchService.search(...);
...
}
}
How can I do the same from groovy?
At first, how I can define @Component
for whole script?
The following code:
@Component class Holder{
@Autowired
SearchService searchService;
def run(){
searchService.search("test");
}
}
new Holder().run()
fails with NPE on searchService
.
I'm running groovyscripts with GroovyClassloader
instatiaded from Java, if it matters.
Thanks a lot in advance!
If you are using @Component
, you should create Spring context as:
def ctx = new GenericApplicationContext()
new ClassPathBeanDefinitionScanner(ctx).scan('') // scan root package for components
ctx.refresh()
or in the XML:
<context:component-scan base-package="org.example"/>
Your code should work if the context is created as above. Here is an example from 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) }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With