SpringでXMLベースでApplicationContextを介してBean定義する方法
Springでorg.springframework.context.support.ClassPathXmlApplicationContextクラスを使用してXMLファイルに記述したクラスをDIする方法です。
XMLファイル(ここではbeanRefContext.xml)を読み込んでApplicationContext(アプリケーションコンテキスト)のインスタンスを生成します。
src/main/resources/beanRefContext.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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クラスのインスタンスを生成している例です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^
資格:少額短期保険募集人,FP3級
コメント