Spring+Struts2, 将框架的配置文件整合起来

来源:互联网 发布:回看 网络电视 编辑:程序博客网 时间:2024/06/05 08:52

    如果我们集成多个框架,那每个框架或多或少都会引入一些xml配置文件到项目中,我们一般的做法就是按照配置文件的默认位置去存放它们,但当我们的项目中壮大到连几角旮旯都充斥着配置文件的话,那我们迫切需要将它们分类管理起来,统一安放。

     就拿Struts1Struts2来说,名字详尽但已有很多的变化,不单单struts2核心机制变了很多,它的核心配置文件也由struts1struts-config.xml更名为struts.xml并且由WEB-INF/下转战到src/下面。这些默认变化都是我们容易犯错的地方。Spring2的配置文件application.xml默认放在src/下面。各种框架有着各自定义好的配置文件信息,如果我们一个个记忆他们的名称、存放地址,岂不是费心费力,很容易犯错。


    我们可以整合这些配置文件,分门别类放在规划好的位置,可以将一个配置文件拆解为多个,可以将文件名称修改的更具体化一些。这样,需要我们有一个映射关系的存在,将逻辑配置文件和实际配置文件相互关联起来,并且根据需要在容器启动的时候加载它们。

 

        下面以Struts2+Spring2为例来整合一下多框架的xml配置文件,因为Struts2要与Spring框架集成,则需要引入Struts2 lib中的struts2-spring-plugin-2.3.4.jar (没有这个jar包会导致无法加载Struts2的核心配置文件)

配置文件共有3个:struts.xmlapplicationContext.xml(改名为spring.xml)web.xml


    暂时将框架的配置文件放到了srcetc包下 ,以此来整体管理配置文件。当然允许我们根据配置类型进行细粒度划分。

 

        spring.xmlstruts.xml中的内容就和我们以前使用SpringStruts2的配置一样,我们只需要修改web.xml文件,将众多配置文件根据需要引入到web.xml文件中即可,如下:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><display-name>SSH2Demo</display-name><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!--设置加载spring的 配置文件 ,注意此处的param-name必须为contextConfigLocation ,因为这是在Spring默认属性名,在加载ContextLoaderListener之后,会根据contextConfigLocation属性名对应的值来替换默认的spring配置文件位置值。--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:com/jizg/etc/spring.xml</param-value></context-param> <listener>        <listener-class>            org.springframework.web.context.ContextLoaderListener        </listener-class>    </listener>        <!-- 配置 struts2,并且配置加载struts2的配置属性(config)值,其中param-name为config也是不可修改的 --><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> <init-param><param-name>config</param-name><param-value>  <!-- 这里是需要的struts配置文件,当修改配置文件位置是,需要将默认的其他几个配置文件加到此处 -->struts-default.xml,struts-plugin.xml,com/jizg/etc/struts.xml</param-value></init-param></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>


当然,除了上面这样的做法,我们还可以借助struts中的<include file=""></include> spring中的<importresource=""/>这两类标签,在配置文件中将以类划分的配置文件统一加载进去,然后再将此文件链接到web.xml中。总之有很多的方式来 整合配置文件,还是看各自的系统结构设计来定吧。

 

          如上这样,把众多分散不一的配置文件整合好,我们系统的结构性增强了,并且针对变化易于修改和检查。




0 0
原创粉丝点击