2009-07-10 3 views
9

私はFileSystemXmlApplicationContextを持っていると私はXMLで定義されたBeanは、コンストラクタの引数として例えば春Beanをファイルからロードする前にBeanをApplicationContextに挿入するにはどうすればよいですか?

で宣言されていないBeanを利用したいと思い、私がやりたい:

<bean class="some.MyClass"> 
    <constructor-arg ref="myBean" /> 
</bean> 

?だから私のような何かを経由してこれをやって想像:誰もが、私はこれを達成することができます方法を知っているん:-(そのようなメソッドが存在しないことを除いて

Object myBean = ... 
context = new FileSystemXmlApplicationContext(xmlFile); 
context.addBean("myBean", myBean); //add myBean before processing 
context.refresh(); 

答えて

15

最初に空の親コンテキストをプログラムで作成し、getBeanFactorySingletonBeanRegistryの実装を返すという事実を使用して、そのコンテキストのBeanFactoryでシングルトンとしてオブジェクトを登録してください。

次に、このコンテキストを "実際の"コンテキストの親として指定します。子コンテキストのBeanは、親のBeanを参照できるようになります。

String[] fs = new String[] { "/path/to/myfile.xml" } 
appContext = new FileSystemXmlApplicationContext(fs, parentContext); 
+0

を! (ちょうどコンパイルするコードを取得する:-) –

+0

ApplicationContextはSingletonBeanRegistryを実装していません –

+0

私はあなたの提案に幸運を払って遊んだことがあります。もっと歓迎されるヘルプ! –

1

私はトラブルAnnotationConfigApplicationContextでこれを解決していたとして、私は次の代替が見つかりました:私はこれをチェックして、あなたをupvoteます

DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); 
beanFactory.registerSingleton("customBean", new CustomBean()); 
context = new AnnotationConfigApplicationContext(beanFactory); 
context.register(ContextConfiguration.class); 
context.refresh(); 
関連する問題