我想使用factory-method用Spring实例化一个bean。但是,诀窍是我想要访问工厂方法中的当前ApplicationContext。
下面是我尝试过的代码:
object ActorSystemFactory {
var applicationContext: ApplicationContext = _
def createActorSystem = {
val system = ActorSystem("AkkaScalaSpring")
SpringExtensionImpl(system)(applicationContext) //need applicationContext here
system
}
}
class ActorSystemFactory extends ApplicationContextAware {
//Spring warns that createActorSystem does not exist here!! and it is...right
//Indeed, it is present in the companion object to make it "static" equivalent.
def setApplicationContext(applicationContext: ApplicationContext) {
ActorSystemFactory.applicationContext = applicationContext
}
}我的xml声明:
<bean id="actorSystem" class="com.myPackage.ActorSystemFactory" factory-method="createActorSystem">
</bean>对于ActorSystemFactory类中的注释,如何处理?
发布于 2014-03-13 17:22:35
好吧,所以我成功做到了。
实际上,现在我不使用静态工厂方法技术,而是使用实例工厂方法技术:
class ActorSystemFactory extends ApplicationContextAware {
def createActorSystem = {
val system = ActorSystem("AkkaScalaSpring")
SpringExtensionImpl(system)
system
}
def setApplicationContext(applicationContext: ApplicationContext) {
ActorSystemFactory.applicationContext = applicationContext
}
}
object ActorSystemFactory {
var applicationContext: ApplicationContext = _
}
<bean id="actorSystemFactory" class="myPackage.ActorSystemFactory"/>
<bean id="actorSystem" factory-bean="actorSystemFactory" factory-method="createActorSystem" />(http://docs.spring.io/spring/docs/3.0.x/reference/beans.html) (不管Spring的版本是什么)
整个工程按预期进行。
发布于 2014-03-13 16:32:59
缺省情况下,spring是单例的。您可以在类中直接实例化参与者系统,而不需要对象。
https://stackoverflow.com/questions/22384189
复制相似问题