Spring Ioc 要点:之一容器的初始化
实例化容器
ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml", "applicationContext-part2.xml"});// of course, an ApplicationContext is just a BeanFactoryBeanFactory factory = (BeanFactory) context;官方推荐的手工方法,ApplicationContext是BeanFactory的一个子类可支持WEB应用.将XML配置文件分拆成多个部分是非常有用的。为了加载多个XML文件生成一个AplicationContext实例,可以将文件路径作为字符串数组传给ApplicationContext构造器。而bean factory将通过调用bean defintion reader从多个文件中读取bean定义。
另外一种方法是使用一个或多个的<import/>元素来从另外一个或多个文件加载bean定义。所有的<import/>元素必须放在<bean/>元素之前以完成bean定义的导入。
<beans><import resource="services.xml"/> <import resource="resources/messageSource.xml"/> <import resource="/resources/themeSource.xml"/> <bean id="bean1" name="code"><context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value></context-param><listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class></listener><!-- or use the ContextLoaderServlet instead of the above listener<servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet>-->
监听器首先检查contextConfigLocation参数,如果它不存在,它将使用/WEB-INF/applicationContext.xml作为默认值。如果已存在,它将使用分隔符(逗号、冒号或空格)将字符串分解成应用上下文将位置路径。ContextLoaderServlet同ContextLoaderListener一样使用'contextConfigLocation'参数。
XML的配置元数据的基本结构
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="..." name="code"><alias name="fromName" alias="toName"/>
这里如果在容器中存在名为fromName的bean定义,在增加别名定义之后,也可以用toName来引用。
考虑一个更为具体的例子,组件A在XML配置文件中定义了一个名为componentA-dataSource的DataSource bean。但组件B却想在其XML文件中以componentB-dataSource的名字来引用此bean。而且在主程序MyApp的XML配置文件中,希望以myApp-dataSource的名字来引用此bean。最后容器加载三个XML文件来生成最终的ApplicationContext,在此情形下,可通过在MyApp XML文件中添加下列alias元素来实现:
<alias name="componentA-dataSource" alias="componentB-dataSource"/><alias name="componentA-dataSource" alias="myApp-dataSource" />这样一来,每个组件及主程序就可通过唯一名字来引用同一个数据源而互不干扰。