SpringでXMLベースでApplicationContextを介してBean定義する方法

SpringでXMLベースでApplicationContextを介してBean定義する方法

Springでorg.springframework.context.support.ClassPathXmlApplicationContextクラスを使用してXMLファイルに記述したクラスをDIする方法です。

XMLファイル(ここではbeanRefContext.xml)を読み込んでApplicationContext(アプリケーションコンテキスト)のインスタンスを生成します。

src/main/resources/beanRefContext.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
  <beans>
    <bean id="context"
    class="org.springframework.context.support.ClassPathXmlApplicationContext">
      <constructor-arg>
        <list>
          <value>bean-xxx.xml</value>
          <value>bean-yyy.xml</value>
        </list>
      </constructor-arg>
    </bean>
  </beans>

ClassPathXmlApplicationContextクラスの引数にbeanRefContext.xmlを指定してApplicationContextのインスタンスを返します。

getBeanでXML内で定義したidを指定してBean定義したインスタンスを取得します。

getBean(“context”)でApplicationContextが取得できます。

別ファイルでBean定義することも可能で、list,valueタグを使ってxmlファイルを指定します。これでbean-xxx.xml,bean-yyy.xmlを取り込んでいます。このファイル内にbean定義を記述します。

以下は、ApplicationContextのインスタンスを取得して、bean-xxx.xml,bean-yyy.xml内で定義されているHogeBeanクラスのインスタンスを生成している例です。

package jp.co.confrage.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import jp.co.confrage.Hoge;
import lombok.Data;

@Configuration
@Data
public class AppConfig {

  private ApplicationContext context;
  private HogeBean hogebean;

  {
    context =
      (ApplicationContext)
      new ClassPathXmlApplicationContext("beanRefContext.xml").getBean("context");
    hogebean = context.getBean("beanのid", HogeBean.class);
  }
}

コメント

タイトルとURLをコピーしました