Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Spring component from groovy

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!

like image 379
tmp120210 Avatar asked Oct 07 '11 15:10

tmp120210


1 Answers

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) }
}
like image 154
tolitius Avatar answered Sep 23 '22 20:09

tolitius