はじめに
Spring Frameworkでは、Bean定義の方法としてXMLベースの設定とJavaベースの設定が存在します。2025年現在は主にJavaベースの設定(@Configuration)が使われていますが、レガシーなシステムでは、未だXMLベースでのbean定義が行われている事があります。
このbeanをApplication Contextに含めるアノテーションを備忘録として残しておきます。
XMLで定義されたBeanをApplication Contextに含めるアノテーション
1. @ImportResource
最も一般的に使用されるアノテーションで、XML設定ファイルをJavaベースの設定にインポートします。
基本的な使い方
@Configuration
@ImportResource("classpath:beans.xml")
public class AppConfig {
}
複数のXMLファイルをインポート
@Configuration
@ImportResource({"classpath:beans1.xml", "classpath:beans2.xml"})
public class AppConfig {
}
2. Spring Bootでの使い方
Spring Bootアプリケーションでは、メインクラスに@ImportResourceを付与する事でインポートできます。
@SpringBootApplication
@ImportResource("classpath:legacy-context.xml")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. テストでのXML設定の使用(@ContextConfiguration)
@ContextConfigurationはテスト専用のアノテーションで、テスト用のApplication Contextを構築する際に使用します。
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath:test-context.xml")
public class LegacyServiceTest {
@Autowired
private LegacyService legacyService;
}
注意点
プロダクションコードでは@ContextConfiguration使用できない
@ContextConfigurationはテスト専用のアノテーションです。通常の@Configurationクラスでは使用できません。
仮にテスト環境で@Configurationを使用している場合は、@ImportResourceを使用する事でApplication Contextに含める事が出来ます。
// 誤った使用例
@Configuration
@ContextConfiguration(locations = "classpath:beans.xml")
public class AppConfig {
}
// 正しい使用例
@Configuration
@ImportResource("classpath:beans.xml")
public class AppConfig {
}
まとめ
XMLで定義されたBeanをApplication Contextに含める主なアノテーションで、基本的な使い分け方は以下です:
-
プロダクションコード:
@ImportResourceを使用 -
Spring Boot: メインクラスまたは
@Configurationクラスに@ImportResourceを付与 -
テストコード:
@ContextConfigurationを使用-
テストコード内に@Configurationがある場合:
@ImportResourceを使用
-
テストコード内に@Configurationがある場合: