問題
大規模なプロジェクト構造では、SpringのBean構成ファイルは、容易な保守性とモジュール性のために異なるフォルダに配置されています。たとえば、共通フォルダの
Spring-Common.xml`、接続フォルダの
Spring-Connection.xml`、ModuleAフォルダの “ Spring-ModuleA.xml`などです。
コード内に複数のSpring Bean設定ファイルをロードすることができます:
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"Spring-Common.xml", "Spring-Connection.xml","Spring-ModuleA.xml"});
すべてのspring xmlファイルをプロジェクトのクラスパスの下に置きます。
project-classpath/Spring-Common.xml project-classpath/Spring-Connection.xml project-classpath/Spring-ModuleA.xml
解決策
上記の方法は整理とエラーの傾向がありません。すべてのSpring Bean構成ファイルを単一のXMLファイルに編成する方がよいでしょう。たとえば、 `Spring-All-Module.xml`ファイルを作成し、Spring Beanファイル全体を次のようにインポートします。
ファイル:Spring-All-Module.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <import resource="common/Spring-Common.xml"/> <import resource="connection/Spring-Connection.xml"/> <import resource="moduleA/Spring-ModuleA.xml"/> </beans>
これで、次のように1つのxmlファイルを読み込むことができます:
ApplicationContext context = new ClassPathXmlApplicationContext(Spring-All-Module.xml);
このファイルをプロジェクトのクラスパスの下に置きます。
project-classpath/Spring-All-Module.xml