在 Spring 中,如果我定义了一个原型(prototype) bean,我可以使用 lookup method injection 注入(inject)它。在 Spring Framework 4.3.0.RELEASE 的当前时间。
在 Grails 中,如何在运行时注入(inject)原型(prototype) bean? Grails 2.5.4 docs显示如何设置 bean.scope = 'prototype"
和 bean.singleton = false
但实际上并没有给出如何注入(inject)非单例 bean 的示例。
最佳答案
我在 Grails 中没有看到太多原型(prototype)范围 bean 的使用,而且我所看到的使用 Spring 文档中描述的模式,该模式直接与 ApplicationContext 一起使用。我假设您可以在 Grails 中使用与 Spring 中相同的方法注入(inject)方法,但这里有一个简单的工厂类,它不涉及 CGLIB 子类化,但在其他方面类似。它确实从 ApplicationContext 中检索了一个原型(prototype)实例,但它隐藏在实现中并且不会弄乱您的应用程序代码:
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,提供原型(prototype) bean 的 bean 名称和 bean 类(在 resources.groovy 或插件的 doWithSpring 中):
beans = {
cartFactory(PrototypeFactory, ShoppingCart, 'shoppingCart')
}
现在您可以注入(inject)工厂 bean 并调用
getInstance()
,并且它将返回一个新的原型(prototype)实例,并且由于它使用泛型,因此您不需要任何强制转换:class SomeClass {
PrototypeFactory<ShoppingCart> cartFactory
...
def someMethod() {
ShoppingCart newCart = cartFactory.instance
...
}
}
您可以重用工厂类为各种原型(prototype) bean 注册任意数量的这些,只要它们具有唯一的 bean 名称。
没有一个名字是重要的,所以改变
getInstance()
更改为您喜欢的任何内容,并将“工厂”更改为“经理”或其他任何内容。
关于spring - 如何在 Grails 中获取原型(prototype) bean 的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38045544/