Spring MVC ClassPathXmlApplicationContextクラスを使ってXMLファイルを読み込む

環境
Spring MVC 5.2.1
Java SE 11

書式
new ClassPathXmlApplicationContext(“general-context.xml")
xmlファイルを読み込んでApplicationContextのインスタンスを生成します。

使用例
1.general-context.xml

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<bean id="context"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>beaninfo001.xml</value>
</list>
</constructor-arg>
</bean>
</beans>
<bean id="context" class="org.springframework.context.support.ClassPathXmlApplicationContext"> <constructor-arg> <list> <value>beaninfo001.xml</value> </list> </constructor-arg> </bean> </beans>
<bean id="context"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>beaninfo001.xml</value>
</list>
</constructor-arg>
</bean>
</beans>

2.Java側コード
getBeanでXML内で定義したidを指定してBean定義したインスタンスを取得します。

サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@Configuration
@Data
public class AppConfig {
private ApplicationContext context;
private UserBean userbean;
{ // ApplicationContextのインスタンスを返す
context = (ApplicationContext)new ClassPathXmlApplicationContext("general-context.xml").getBean("context");
// ApplicationContextを取得
userbean = context.getBean("userbean",UserBean.class)
}
}
@Configuration @Data public class AppConfig { private ApplicationContext context; private UserBean userbean; { // ApplicationContextのインスタンスを返す context = (ApplicationContext)new ClassPathXmlApplicationContext("general-context.xml").getBean("context"); // ApplicationContextを取得 userbean = context.getBean("userbean",UserBean.class) } }
@Configuration
@Data
public class AppConfig {
  
  private ApplicationContext context;
  private UserBean userbean;
  
  { // ApplicationContextのインスタンスを返す
    context = (ApplicationContext)new ClassPathXmlApplicationContext("general-context.xml").getBean("context");
      // ApplicationContextを取得
    userbean = context.getBean("userbean",UserBean.class)	
   }


}

 

SpringMVC

Posted by arkgame