Call Spring component from groovy

I have a spring based java application with some useful components. As part of the system, I have a groovy script to process some reports. I would like to name the spring component from a groovy script. When I write in Java, I need to use annotation @Autowiredinside @Component, i.e.

@Component
class Reporter{
@Autowired
SearchService searchService;

void report(){
 searchService.search(...);
 ...
}
}

How can I do the same from groovy? First, how can I define @Componentfor integer script? The following code:

@Component class Holder{
    @Autowired
    SearchService searchService;

    def run(){
        searchService.search("test");
    }
}

new Holder().run()

does not work with NPE on searchService. I am running groovyscripts with GroovyClassloaderinstalled with Java, if that matters. Thank you very much in advance!

+5
source share
2 answers

@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) }
}
+4

:

  • Groovy , , bean <context:component-scan>. , , GroovyClassLoader.

  • Spring <lang:groovy> bean GroovyClassLoader. <lang:property> @Autowired.

  • GroovyClassLoader, bean AutowiredAnnotationBeanPostProcessor.

, obj , GroovyClassLoader:

AutowiredAnnotationBeanPostProcessor aabpp =
    (AutowiredAnnotationBeanPostProcessor)applicationContext.
        getBean(AnnotationConfigUtils.AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME);

aabpp.processInjection(obj);

, , GroovyClassLoader, " " .

+1

All Articles