Spring /在一个bean的工厂方法中访问当前的applicationContext

时间:2014-03-13 14:49:38

标签: java spring scala

是否有可能获得对当前ApplicationContext的实际引用? :

    package myPackage;
    public class AFactory {

       public static A createA() {
          // I need to access to the current instance of ApplicationContext here, passing it to another object's method for example 
       }

    }

在我的applicationContext.xml

<bean id="myBeanA" class="myPackage.AFactory" factory-method="createA">
</bean>

更新------------------------------------------- -------------

我认为使用Java的一个例子会更受欢迎,并且可以在Scala中使用,但由于事实上&#34;静态&#34;它在Scala中比较棘手。方法在类外定义:

object ActorSystemFactory {

  var applicationContext: ApplicationContext = _

  def createActorSystem = {
    val system = ActorSystem("AkkaScalaSpring")
    SpringExtensionImpl(system)(applicationContext)
    system
  }
}

class ActorSystemFactory extends ApplicationContextAware {

  def setApplicationContext(context: ApplicationContext) {
    ActorSystemFactory.applicationContext = context
  }

}

对于那些了解Scala的人,Spring在逻辑上警告这个类中没有createActorSystem静态方法的事实。

有人曾经处理过此案吗?

1 个答案:

答案 0 :(得分:3)

让你的bean实现ApplicationContextAware

public class AFactory implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}