在Spring中,如果我定義了一個原型bean,我可以在Spring Framework 4.3.0.RELEASE的當前時間使用lookup method injection注入它。如何在Grails中獲取prototype bean的實例?
在Grails中,我如何在運行時注入原型bean? Grails 2.5.4 docs顯示如何設置bean.scope = 'prototype"
和bean.singleton = false
,但實際上並沒有給出如何注入非單例bean的示例。
在Spring中,如果我定義了一個原型bean,我可以在Spring Framework 4.3.0.RELEASE的當前時間使用lookup method injection注入它。如何在Grails中獲取prototype bean的實例?
在Grails中,我如何在運行時注入原型bean? Grails 2.5.4 docs顯示如何設置bean.scope = 'prototype"
和bean.singleton = false
,但實際上並沒有給出如何注入非單例bean的示例。
我在Grails中還沒有看到太多原型範圍bean的用法,而且我見過的東西使用了直接與ApplicationContext一起工作的Spring文檔中描述的模式。我假設你可以在Spring中使用的Grails中使用相同的方法注入方法,但這裏有一個簡單的工廠類,它不涉及CGLIB子類,但在其他方面類似。它檢索來自ApplicationContext的原型實例,但是這隱藏在執行和不搞亂你的應用程序代碼:
package com.yourcompany
import groovy.transform.CompileStatic
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
@CompileStatic
class PrototypeFactory<T> implements ApplicationContextAware {
ApplicationContext applicationContext
final Class<T> beanClass
final String beanName
PrototypeFactory(Class<T> beanClass, String beanName) {
this.beanClass = beanClass
this.beanName = beanName
}
T getInstance() {
applicationContext.getBean(beanName, beanClass)
}
}
要使用它,註冊該類的豆,提供bean的名稱和bean類bean原型的(在resources.groovy,或在插件的doWithSpring):
beans = {
cartFactory(PrototypeFactory, ShoppingCart, 'shoppingCart')
}
現在你可以因爲它使用泛型你注入的工廠bean,並調用getInstance()
,它會返回一個新的原型實例,不需要任何演員表:
class SomeClass {
PrototypeFactory<ShoppingCart> cartFactory
...
def someMethod() {
ShoppingCart newCart = cartFactory.instance
...
}
}
只要具有唯一的bean名稱,就可以重用工廠類來根據需要爲各種原型bean註冊儘可能多的這些類。
沒有任何名稱是重要的,所以將getInstance()
更改爲您喜歡的任何內容,然後將「工廠」更改爲「經理」或其他。