0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Spring Framework】XMLで定義されたBeanをApplication Contextに含める方法

Last updated at Posted at 2025-09-23

はじめに

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を使用
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?