Spring bean加載多個配置文件


  除了寫很簡單的加載一個xml,加載多個的情況一直沒用到,在公司里也不會由自己處理這個問題,現在需要用到了,就研究驗證一下。

  使用的案例還是上面的例子。

  只有,將原來的beans.xml分成兩個部分。

  

1.結構

  

 

2.beans.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <!--
 7         加載一個xml,這個作為總的xml入口
 8     -->
 9     <import resource="beans2.xml"/>
10 
11     <bean id="helloWorldService" class="com.it.bean.HelloWorldService">
12         <property name="helloWorld" ref="springHelloWorld"/>
13     </bean>
14 
15 
16 </beans>

 

3.beans2.xml

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5 
6     <bean id="springHelloWorld" class="com.it.service.SpringHelloWorld"></bean>
7     
8 </beans>

 

4.運行類

 1 package com.it.main;
 2 
 3 import com.it.service.HelloWorld;
 4 import com.it.bean.HelloWorldService;
 5 import org.springframework.context.ApplicationContext;
 6 import org.springframework.context.support.ClassPathXmlApplicationContext;
 7 
 8 public class HelloMain {
 9     public static void main(String[] args) {
10 
11         ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
12 
13         HelloWorldService service = (HelloWorldService) context.getBean("helloWorldService");
14 
15         HelloWorld hw= service.getHelloWorld();
16 
17         hw.sayHello();
18     }
19 }

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM