2009-07-07 15 views
14

私のプログラムでは、プログラムでApplicationContextを設定する必要があります。具体的には、MyClassのインスタンスへの参照があり、 "xxyy"という新しいBeanとして定義したいと考えています。プログラムで特定のBeanオブジェクトを設定する - Spring DI

public void f(MyClass mc, ApplicationContext ac) { 
    // define mc as the "xxyy" bean on ac ??? 
    ... 
    ... 

    // Now retrieve that bean 
    MyClass bean = (MyClass) ac.getBean("xxyy"); 

    // It should be the exact same object as mc 
    Assert.assertSame(mc, bean); 
} 

BeanDefinitionのAPIは、私は、インスタンスを指定したいので、それは私のために動作しませんので、私は、新しいbeanのクラスを指定してみましょう。 私は解決策を見つけることができましたが、このような目立つ目的のためにあまりにも多くのコードのように思われる2つの追加の工場豆が必要でした。

私のニーズに対応する標準APIはありますか?

答えて

16

あなたは、このコンテキストを使用することができます。

mockContext.getBeanFactory().registerSingleton("name", reference); 

と現実の文脈で

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
      new String[] { "real-context.xml" }, mockContext); 

をそれをプラグインし、クラスがある持っている

GenericApplicationContext mockContext = new GenericApplicationContext(); 

import org.springframework.context.support.ClassPathXmlApplicationContext; 

import org.springframework.context.support.GenericApplicationContext; 
+0

私はこれを麦わらにすることはできません:(私のctxは親のものの代わりに子のbeanを取得します... –

12

これを行うには、いくつかのフープをジャンプする必要があります。最初のステップは、コンテキストの基礎となるBeanFactory実装への参照を取得することです。これは、コンテキストがConfigurableApplicationContextを実装している場合にのみ可能です。これは、標準のコンテキストのほとんどが行います。そのBeanファクトリでインスタンスをシングルトンとして登録することができます。

ConfigurableApplicationContext configContext = (ConfigurableApplicationContext)appContext; 
SingletonBeanRegistry beanRegistry = configContext.getBeanFactory(); 
beanRegistry.registerSingleton("xxyy", bean); 

このようなコンテキストにオブジェクトを挿入することはできます。

+1

これは私の命を救った! – jmcg

関連する問題