示例应用程序位于此处:https://github.com/rushidesai1/Grails2_4_2_BeanIssue
问题:
在 resources.groovy 中,如果我们声明一个像这样的 bean
beans = {
testObject(TestObject){bean ->
bean.scope = "prototype"
map = new HashMap() // or [:]
//And also if we declare any object like this
testA = new TestA()
}
}
现在,如果我们 DI testObject bean 或执行“Holders.grailsApplication.mainContext.getBean("testObject")”,那么我们获得的 bean 将具有单例“map”和单例“testA”对象。
这里 testObject 被声明为“prototype”,即使如此,“map”和“testA”都是单例
我想知道这是否是一个错误,或者它是否按设计工作。它会像这样工作是完全违反直觉的,因为我们专门做新的事情,所以我们期望每次都会注入(inject)一个新的bean。
使用单元测试用例查看我的问题的更详细版本。
提前感谢您的澄清!!!
最佳答案
I want to know if this is a bug or it is working as designed.
是的,我认为它正在按设计工作。
你的testObject
bean是一个单例。该单例 bean 仅具有 map
和 testA
属性的 1 个副本。您所描述的行为正是我所期望的。
编辑:
我已经审查了链接项目中的应用程序,这就是正在发生的事情......
在resources.groovy
中你有这样的东西:
测试对象(测试对象){ bean ->
bean.scope =“原型(prototype)”
mapIssue1 = ["key1FromResource.groovy": "value1FromResource.groovy"]
}
该 testObject
bean 是一个原型(prototype)作用域 bean,因此每次检索一个 bean 时,您都会获得一个新实例。但是,您在 bean 定义中硬编码了初始化 Map
,因此创建的 bean 定义具有与其关联的 Map
,因此从该 bean def 创建的每个 bean 都将具有相同的 map
。如果您想要不同的 Map
实例,您可以在 afterPropertiesSet
或类似内容中创建它。
单元测试位于 https://github.com/rushidesai1/Grails2_4_2_BeanIssue/blob/e9b7c9e70da5863f0716b998462eca60924ee717/test/unit/test/SpringBeansSpec.groovy写得不是很好。要了解发生了什么,需要在所有这些 println 之后询问标准输出。可以通过以下方式更简单地验证该行为:
资源:groovy
import test.TestObject
beans = {
testObject(TestObject) { bean ->
bean.scope = "prototype"
mapIssue1 = ["key1FromResource.groovy":"value1FromResource.groovy"]
}
}
SpringBeansSpec.groovy
package test
import grails.test.mixin.TestMixin
import grails.test.mixin.support.GrailsUnitTestMixin
import spock.lang.Specification
@TestMixin(GrailsUnitTestMixin)
class SpringBeansSpec extends Specification {
static loadExternalBeans = true
void 'test bean properties'() {
setup:
def testObject1 = grailsApplication.mainContext.testObject
def testObject2 = grailsApplication.mainContext.testObject
expect: 'test TestObject beans are not the same instance'
!testObject1.is(testObject2)
and: 'the TestObject beans share values defined in the bean definition'
testObject1.mapIssue1.is(testObject2.mapIssue1)
}
}
关于spring - Grails 2.4.2 bean spring bean注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39137578/