拆分思路
将所有的配置内容,放在一个applicationContext.xml.配置内容的可读性、可维护性变差。通常需要把applicationContext.xml分解成多个细粒度的配置文件,在每个配置文件中只配置某一个模块。
分解的两种思路:
(1)三层架构的分层模式
将DAO、Service、controller(或action、servlet)层,以及公用配置(如数据源、事务)各写在一个单独的配置文件中。
(2)将每一个模块功能,单独写在一个配置文件之中。
例如将“学生管理”模块和“部门管理模块”各写在一个配置文件之中。其次,再将公用配置单独写在一个配置文件中。
Spring配置文件的路径
在Web服务启动时,就自动启动Spring容器,然后让Spring容器来为其他框架提供服务。但是在Web项目中,无法像普通应用那样在main()方法里,通过创建ApplicationContext对象来启动Spring容器。是通过在web.xml配置一个用于Web容器的监听器(Listener),从而让Spring容器在Web容器初始化时自动启动。
Spring就提供了这样一个Listener:org.springframework.web.context.ContextLoaderListener
Listener在spring-web-x.x.x.RELEASE.jar包下,因此我们使用Spring开发Web项目时,至少需要在WEB-INF的lib目录里导入以下6个包:
spring-aop-4.xx.RELEASE.jar | spring-context-4.xx.RELEASE.jar | spring-beans-4.xx.RELEASE.jar |
---|---|---|
spring-core-4.xx.RELEASE.jar | spring-expression-4.xx.RELEASE.jar | commons-logging-1.1.3.jar |
Listener的具体配置如下:
web.xml
<!-- 指定Spring配置文件(如applicationContext.xml)的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<!-- 通过ContextLoaderListener,初始化Spring容器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
其中参数名contextConfigLocation对应的参数值(<param-value>
)用来指定Spring配置文件的路径。如果配置文件的路径是 “/WEB-INF/applicationContext.xml”则可省略此<context-param>
的配置,即“/WEB-INF/applicationContext.xml”是Spring配置文件的默认“约定”路径;否则,就必须通过contextConfigLocation参数名来指定具体路径。其中classpath代表资源路径(例如项目的src目录)。
配置文件拆分后的整合方法
在web.xml里,通过contextConfigLocation的<param-value>
来指定Spring配置文件的路径。
如果我们将Spring配置文件拆分成了多个,我们就可以通过以下方法来将它们组装在一起:将拆分后的配置文件全部写在<param-value>
中,并用英文逗号分隔开。如下,
web.xml
<!-- 指定Spring配置文件(如applicationContext.xml)的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml,
classpath:applicationContext-controller.xml,
classpath:applicationContext-service.xml,
classpath:applicationContext-dao.xml,
</param-value>
</context-param>
<!-- 通过ContextLoaderListener,初始化Spring容器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
还可以使用“*”来模糊匹配:
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml,
classpath:applicationContext-*.xml,
</param-value>
</context-param>
还可以直接在Spring配置文件中,通过import元素导入其他配置文件。从而将若干配置文件整合到一起:
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="… "
xmlns:xsi="…"
xmlns:p="…"
xsi:schemaLocation="…">
<import resource="applicationContext-controller.xml"/>
<import resource="applicationContext-service.xml"/>
<import resource="applicationContext-dao.xml"/>
<bean…
…
</beans>