Kim*_*ble 4 grails dependency-injection
假设我在grails-app/services下有一个BarService,在src/groovy下有一个常规的Groovy类'Foo'.
class Foo {
def barService
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在运行时以编程方式将其转换为Spring bean?为了澄清,我想获得一个注入barService字段的BarService引用.
def fooInstance = new Foo()
magic-create-spring-bean-function(fooInstance)
assert fooInstance.barService
Run Code Online (Sandbox Code Playgroud)
请参阅此答案,了解如何获取applicationContext的实例.可以通过以下方式连接bean属性:
def ctx = ...
def foo = new Foo()
ctx.beanFactory.autowireBeanProperties(foo, ctx.beanFactory.AUTOWIRE_BY_NAME, false)
Run Code Online (Sandbox Code Playgroud)
我建议使用常规的spring bean(可能是原型范围)而不是这种方法.