如何在Groovy spring DSL

时间:2015-09-01 11:48:48

标签: spring grails-3.0

在grails中,使用spring groovy DSL

定义resources.groovy中的spring bean
beans = {
    myBean(MyBeanImpl) {
        someProperty = 42
        otherProperty = "blue"
        bookService = ref("bookService")
    }
}

如何使用此DSL定义原型范围的bean?我在documentation

中找不到任何相关内容

2 个答案:

答案 0 :(得分:8)

这应该有效:

beans = {
    myBean(MyBeanImpl) { bean ->
        bean.scope = 'prototype'
        someProperty = 42
        otherProperty = "blue"
        bookService = ref("bookService")
    }
}

答案 1 :(得分:0)

我同意杰夫斯科特布朗的观点。

你怎么知道它不起作用?我们正在使用Grails 2.3.9。

我在我的resources.groovy中有这个:

httpBuilderPool(HTTPBuilder) { bean ->
    bean.scope = 'prototype'    // A new service is created every time it is injected into another class
    client = ref('httpClientPool')
}

...

这在Spock集成测试中:

import grails.test.spock.IntegrationSpec
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.log4j.Logger

class JukinHttpBuilderSpec extends IntegrationSpec {

    private final Logger log = Logger.getLogger(getClass())

    def httpBuilderPool
    def grailsApplication

    void "test jukinHttpBuilder instantiates"() {
        expect:
        httpBuilderPool
        httpBuilderPool.client instanceof CloseableHttpClient
    }

    void "test httpBuilderPool is prototype instaance"() {
        when: 'we call getBean on the application context'
        def someInstanceIds = (1..5).collect { grailsApplication.mainContext.getBean('httpBuilderPool').toString() }.toSet()
        log.info someInstanceIds.toString()

        then: 'we should get a new instance every access'
        someInstanceIds.size() == 5
    }

    void "test injected httpBuilderPool is prototype instance"() {
        when: 'we access the injeted httpBuilderPool'
        def someInstanceIds = (1..5).collect { httpBuilderPool.toString() }.toSet()
        log.info someInstanceIds.toString()

        then: 'it uses the same instance every time'
        someInstanceIds.size() == 1
    }
}

这表明我在2.3.9中工作。