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 }

 

 

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值