2016-04-25 5 views
1

は、私は私の春のJavaモジュール二つの異なるXMLファイルとSpringで2つのApplicationContextを互いにマージするには?

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
      "SpringBeans.xml"); 

ClassPathXmlApplicationContext helloContext = new ClassPathXmlApplicationContext("HelloBeans.xml"); 

で2つのコンテキストを持っています。今ではHelloBeans.xmlのbeanをcontextから取得し、SpringBeans.xmlのbeanをhelloContextからコンテキストをリフレッシュせずに取得する必要があります。

+0

見てみてください - http://stackoverflow.com/questions/6973783/register-additional-beans-from -xml-definition-into-application-context-that-a – asg

+0

親を設定すると片方向のアクセスしか許可されず、親を経由して子のBeanにアクセスすることはできません –

答えて

0

あなたは(たとえばAllBeans.xml用)親Springコンテキストファイルを作成し、SpringBeans.xmlHelloBeans.xmlインポートすることもできます

<import resource="classpath:SpringBeans.xml" /> 
<import resource="classpath:HelloBeans.xml" /> 

を、コードはなる:

ClassPathXmlApplicationContext SuperContext = new ClassPathXmlApplicationContext("AllBeans.xml"); 
+0

'context'と' helloContext'だけを使用する必要があります –

0

コードの下にしようとすると、「helloContextを使用します"最後に:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml"); 
ClassPathXmlApplicationContext helloContext = new ClassPathXmlApplicationContext("HelloBeans.xml"); 

helloContext.setParent(context); 
helloContext.setClassLoader(context.getClassLoader()); 
helloContext.refresh(); 
helloContext.registerShutdownHook(); 
+0

便利ではない、すでにすべてを試した –

+0

私のテストケースでは問題ありません。あなたのコードや設定を表示してください。 –

+0

コンテキストをリフレッシュせずに 'helloContext'からSpringBeans.xmlの' context'とBeanからHelloBeans.xmlのBeanを取得する必要があります。 –

1

は私が探していたものを見つけることができませんでしたが、これは私が行うことができる最高です:

PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver(
      context.getClassLoader()); 
Resource resource = pathMatchingResourcePatternResolver 
      .getResource("classpath:HelloBeans.xml"); 
AutowireCapableBeanFactory factory = context 
      .getAutowireCapableBeanFactory(); 
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory; 
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(
      registry); 
xmlReader.loadBeanDefinitions(resource); 
関連する問題