views:

526

answers:

1

Let's say that I've got a BarService under grails-app/services and regular Groovy class 'Foo' like this under src/groovy.

class Foo {
  def barService
}

Are there any way to turn this into a Spring bean programmatically at runtime? Just to clarify, I want to get a reference to BarService injected into the barService field.

def fooInstance = new Foo()
magic-create-spring-bean-function(fooInstance)
assert fooInstance.barService
+2  A: 

See this answer on how to obtain the instance of the applicationContext. Wiring the bean properties can be done this way:

def ctx = ...
def foo = new Foo()
ctx.beanFactory.autowireBeanProperties(foo, ctx.beanFactory.AUTOWIRE_BY_NAME, false)

I would suggest using regular spring beans (maybe prototype-scoped) rather than this approach, though.

Siegfried Puchbauer