【问题标题】:How to define a prototype scoped bean in Groovy spring DSL如何在 Groovy spring DSL 中定义原型作用域 bean
【发布时间】:2015-11-26 15:27:21
【问题描述】:

在 grails 中,使用 spring groovy DSL 在 resources.groovy 中定义 spring bean

beans = {
    myBean(MyBeanImpl) {
        someProperty = 42
        otherProperty = "blue"
        bookService = ref("bookService")
    }
}

如何使用这个 DSL 定义原型作用域 bean?我在documentation 中找不到任何关于此的内容@

【问题讨论】:

  • “我在文档中找不到任何关于此的内容” - 在第 18.3 节下,有一个示例将 sessionFactory bean 配置为请求范围。该示例没有具体说明如何配置原型作用域 bean,但所有作用域的语法都是相同的。只需将“请求”替换为“原型”即可。
  • @JeffScottBrown 抱歉,我错过了。我在该文档中浏览并搜索了原型

标签: spring grails-3.0


【解决方案1】:

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

你怎么知道它不起作用?我们正在使用 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 中有效。

【讨论】:

    【解决方案2】:

    这应该可行:

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

    【讨论】:

    • 这对我不起作用。我正在使用 grails 2.4.4。你能提供一些帮助吗?
    • @Richa 不知道自己在做什么,尤其是什么不起作用,很难提供帮助。上面显示的内容确实有效,并且一直有效。您的应用程序中一定还有其他因素使事情变得复杂。
    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 2013-08-05
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2018-07-02
    相关资源
    最近更新 更多