mzzzzb
mzzzzb

Reputation: 1452

How to define a prototype scoped bean in Groovy spring DSL

In grails one defines spring beans in resources.groovy using the spring groovy DSL

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

How do you define prototype scoped bean using this DSL? I couldnt find anything on this in the documentation

Upvotes: 4

Views: 1160

Answers (2)

jerryb
jerryb

Reputation: 1639

I agree with Jeff Scott Brown.

How do you know it doesn't work? We're using Grails 2.3.9.

I have this in my resources.groovy:

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

...

and this in a Spock Integration Test:

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

which shows me it works in 2.3.9.

Upvotes: 0

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

This should work:

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

Upvotes: 8

Related Questions