0

I have an Spring-powered app and want to integrate groovy. Specifically, I have one abstract java class with a set of abstract method definitions and one repository inyected with autowired.

This class must be implemented by several final groovy external classes (one for each client).

At this moment, I am calling the Groovy class in java this way:

final Class parsedClass = groovyClassLoader.parseClass(groovyFile);
final GroovyObject groovyObject = (GroovyObject) parsedClass.newInstance();
final Object response = groovyObject.invokeMethod(methodName, methodParameters);

The problem is that I need to autowired the repository variable in each Groovy external class but currently are null.

How can I notify the Groovy class to get the inyected repository variable when I create it at runtime?

Thanks!

Edit

Y have solved it using the setProperty method from groovyObjectObject this way:

groovyObject.setProperty("myRepository", myRepositoryImpl);
Antonio Acevedo
  • 1,480
  • 3
  • 21
  • 39

2 Answers2

1

The instance here is not created by spring, hence I don't think spring can automagically set the instance of repository in the groovyObject that you have.

However, if you can can autowire the repository into the class thats generating the groovyObject then you can manually inject the repo in the newInstance call.

parsedClass.newInstance(repository:your_autowired_repo_ref)

kdabir
  • 9,623
  • 3
  • 43
  • 45
  • Hi kunal, the groovy.lang.GroovyObject class has not newInstance method with parameters, only a non-parameter method so I cannot do that this way. – Antonio Acevedo Feb 04 '14 at 21:26
  • I tried it with a contrived example and it worked. `class Person {def name}` `def p = Person.class.newInstance(name:"test")` and then `assert 'test'==p.name` – kdabir Feb 05 '14 at 02:36
  • You are using the `Person.class.newInstance(name:"test")` with Groovy sintax (because you think I make the call from a .groovy class) but in my case the call is made from a .java class so I am limited to the `groovy.lang.GroovyObject'`java package (I am using groovy-all dependency from `org-codehaus.groovy`), which has only one new instance method with no parameters – Antonio Acevedo Feb 05 '14 at 08:05
  • Got that, makes sense to me now :) – kdabir Feb 06 '14 at 00:58
0

I have solved it using the setProperty method from groovyObjectObject this way:

groovyObject.setProperty("myRepository", myRepositoryImpl);
Antonio Acevedo
  • 1,480
  • 3
  • 21
  • 39