【问题标题】:Grails: Dependency injection in regular groovy classGrails:常规 groovy 类中的依赖注入
【发布时间】:2009-11-04 17:28:55
【问题描述】:

假设我在 grails-app/services 下有一个 BarService,在 src/groovy 下有一个像这样的常规 Groovy 类 'Foo'。

class Foo {
  def barService
}

有没有办法在运行时以编程方式将其转换为 Spring bean?澄清一下,我想将 BarService 的引用注入到 barService 字段中。

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

【问题讨论】:

    标签: grails dependency-injection


    【解决方案1】:

    请参阅this answer,了解如何获取 applicationContext 的实例。可以通过这种方式连接 bean 属性:

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

    不过,我建议使用常规 spring bean(可能是原型范围)而不是这种方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 1970-01-01
      • 2021-02-24
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多