【问题标题】:Groovy Spring DSL: constructing beans with properties of other beansGroovy Spring DSL:使用其他 bean 的属性构造 bean
【发布时间】:2012-07-19 23:33:01
【问题描述】:

我有一堆 Spring bean,其中一些需要从其他 bean 初始化,其中一些需要从其他 bean 的属性初始化。例如:

Foo {
}

Bar {
    String getBaz()
}

Qux {
    Qux(Foo foo, String baz)
}

我想我可以写一些类似的东西

beans = {
    foo(Foo) {}
    bar(Bar) {}
    qux(Qux, ref('foo'), ref('bar').baz) {}
}

但显然这不起作用,因为 ref('bar') 不是 Bar,而是 RuntimeBeanReference

在纯 Spring (3+) 中,spring expressions 显然可以实现我想要的,但我无法使用 Grails Spring DSL 找出必要的语法。可以吗?

【问题讨论】:

    标签: spring grails


    【解决方案1】:

    我认为你的意思是类看起来像这样:

    class Foo {
    }
    
    class Bar {
       String baz
    }
    
    class Qux {
       Foo foo
       String baz
    
       Qux(Foo f, String b) {
          foo = f
          baz = b
       }
    }
    

    第二个ref('foo') 应该是ref('bar')。然后这将起作用:

    beans = {
       foo(Foo)
       bar(Bar) {
          baz = 'wazzup'
       }
       qux(Qux, ref('foo'), '#{bar.baz}')
    }
    

    【讨论】:

    • Burt,这仅适用于构造函数吗?我试过bean(MyService){ prop = '#{anotherBean.foo()}' },但没用,空指针。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 2011-06-03
    • 2018-09-08
    • 2020-05-03
    相关资源
    最近更新 更多