複数のSpring Bean設定ファイルを読み込む方法

複数のSpring Bean構成ファイルをロードする方法

問題

大規模なプロジェクト構造では、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ファイルを作成し、次のようにSpringBeanファイル全体をインポートします。

ファイル:Spring-All-Module.xml



    
        
        

これで、次のような単一のxmlファイルをロードできます。

    ApplicationContext context =
            new ClassPathXmlApplicationContext(Spring-All-Module.xml);

このファイルをプロジェクトクラスパスの下に配置します。

    project-classpath/Spring-All-Module.xml

Note
Spring3では、代替ソリューションはJavaConfig @Importを使用しています。