Spring 怎样加载多个bean 配置文件
2017-05-27 10:34
495 查看
对于大多数的应用,从表现层的action,到持久层的DataSource,都被Spring 作为bean 管理。如果这些bean 被配置在同一个文件中,阅读及维护该配置文件将是一件非常有挑战的事情。
因此, Spring 建议:将一个大的配置文件分解成多个小的配置文件,使每个配置文
件仅仅管理功能近似于bean; 这样不仅可以分散配置文件,降低修改配置文件的风险,
而且更符合"分而治之"的软件工程原理。
多个配置文件最终需要汇总, ApplicationContext提供如下方式来汇总多个配置文件:
.使用App1icationContext 加载多个配置文件。
• Web 应用启动时加载多个配置文件。
• XML 配置文件中导入其他配置。
1 ApplicationContext 加载多个配置文件
ApplicatonContext 的常用实现类有如下两个:
• ClassPathXm1 ApplicationContext 。
• FileSystemXm1ApplicationContext 。
这两个类都可以用来加载多个配置文件,它们的构造器都可以接收一个数组,并在
该数组中存放多个配置文件。ClassPathXm1ApplicationContext 可采用如下代码加载多个
配置文件:
/I创建配置文件数组
/I假设有3 个配置文件: a.xml , b.xml , c.xml
Str工ng[) configLocations = {"a.xml" , "b.xml" , "c.xml"}
以配置文件数组为参数,创建ApplicationContext
ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocations);
与采用FileSystemXm1ApplicationContext创建ApplicationContext的方式相似,区别
仅在于二者搜索配置文件的路径不同:ClassPathXm1ApplicationContext通过CLASSPATH
路径搜索配置文件:而FileSystemXm1ApplicationContext则在当前路径搜索配置文件。
2 Web 应用启动时加载多个配置文件 参看5.12.3 节所述,通过ContextLoaderListener 也可加载多个配置文件,可利用 337 轻量级J2EE 企业应用实战一一-Struts+Spring+Hibernate 整合开发 <context-pararn>元素来指定多个配置文件位置,其配置如下: <l-- 确定配置文件的位置一〉 <context-param> <param-name>contextConfigLocation</param-name>
<1-- 此处可以列出多个Spring 的XML 配置文件>
<param-value>/WEB-INF/daoContext.xml IWEB-INF/applicationContext.xml<1
param-value>
<context-param>
3 XML 配置文件中导人其他配置文件 配置文件本身和其子元素import. 可用于导入其他配置文件。具体的配置示例如下: <?xml version="1.0" encod工口g="gb2312"?> <!一指定Spring 配置文件的dtd> <!DOCTYPE beans PUBLIC "-IISPR工NGIIDTD BEANIIEN" ''htt p:/ /ww w.springframe work.o rg/dtd/spring-beans.dtd''> <!-- Spring 配置文件的根元素-> <beans>
<!一导入第→份配置文件: serv工ces.xml一〉 <import resource="serv工ces.xml"l> <!-- 导入第二份配置文件: resources/messageSource.xml 一〉 <import resource="resources/messageSource.xml"l> <!-- 导入第二份配置文件: resourcesl themeSource.xml --> <import resource="/resources/themeSource.xml"l>
<!-- 下面定义该文件垦的其他bean…〉 <bean id="bean1" class=". .."> <bean id="bean2" class="..."> </beans>
相关文章推荐
- JSP页面怎样调用Spring配置文件中定义的Bean
- 快速上手Spring--3. 加载Bean的配置文件
- Spring bean加载多个配置文件
- 快速上手Spring 加载Bean配置文件
- Spring配置文件加载时出现Bean property 'newscontentDAO' is not writable or has an invalid setter method错误的解决
- Spring源码分析:Bean加载流程概览及配置文件读取
- eclipse中Spring的配置文件不在src目录下加载bean失败的解决方案
- Spring源码分析:Bean加载流程概览及配置文件读取
- Spring (一) 加载配置文件,实例化类, 三种实例化bean的方式
- spring在javaWeb环境中加载 bean 配置文件方式的选择
- spring加载多个bean配置文件案例
- 快速上手Spring--3. 加载Bean的配置文件
- Spring读取xml配置文件并加载bean对象
- 快速上手Spring--3. 加载Bean的配置文件
- Spring如何利用XmlBeanFactory类加载bean的配置文件?
- spring学习总结(六):IOC & DI 配置Bean之作用域、加载外部属性文件、SPEL
- 在Maven项目中加载spring中的bean的配置xml文件会提示找不到解决方法
- Spring源码分析之配置文件加载并注册Bean
- Spring 源码分析:Bean 加载流程概览及配置文件读取
- Spring配置文件加载时出现Bean property 'newscontentDAO' is not writable or has an invalid setter method错误的解决[00原创]