2015-09-01 25 views
3

Grails中一个在resources.groovy定义的Spring bean利用弹簧常规DSL如何定义原型

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

你如何定义原型使用这种DSL范围的bean作用域的bean在Groovy春天DSL?我无法找到在documentation

+0

“我在文档中找不到任何东西” - 在第18.3节中,有一个示例将sessionFactory bean配置为请求作用域。该示例没有具体说明如何配置原型范围的bean,但所有范围的语法都是相同的。只需将“请求”替换为“原型”即可。 –

+0

@JeffScottBrown对不起,我错过了。我在该文档中掠过并搜索了原型 – mzzzzb

回答

7

这个东西这应该工作:杰夫·斯科特·布朗

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

这不适用于我。我正在使用grails 2.4.4。你能提供一些帮助吗? – Richa

+0

@Richa不知道你在做什么,特别是没有工作,提供帮助将非常困难。上面显示的是有效的,并且一直有效。在你的应用程序中必须有一些其他因素使事情变得复杂。 –

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') 
} 

... 

,这在斯波克集成测试:

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。