Spring+Mybatis+SpringMVC 整合 XML

首先我们需要了解的是有几个配置文件?

  • 基础的web.xml

1、spring-mybatis.xml:spring本身的配置,以及spring的数据库配置(即与mybatis的联合配置)
2、spring-mvc.xml:springMVC的配置,例如定义了controller、service等
3、mybatis-config.xml:mybatis本身的一些设置

其次是如何调用的?
第一个元素,调用了spring-mybatis.xml

<!--全局范围内环境参数初始化-->
<context-param>
    <!--参数名称-->
    <param-name>contextConfigLocation</param-name>
    <!--参数取值-->
    <param-value>classpath:spring/spring-mybatis.xml</param-value>
</context-param>

第二个元素,调用了spring-mvc.xml

<!---servlet配置-->
<!--用来声明一个servlet的数据 -->
<servlet>
    <!--指定servlet的名称-->
    <servlet-name>dispatcher</servlet-name>
    <!--指定servlet的类名称,这里配置了前端控制器-->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--用来定义参数,可有多个init-param。在servlet类中通过getInitParamenter(String name)方法访问初始化参数    -->
    <init-param>
        <param-name>contextConfigLocation</param-name>  <!--参数名称-->
        <param-value>classpath:spring/spring-mvc.xml</param-value> <!--参数值-->
    </init-param>
    <!--当值为正数或零时:Servlet容器先加载数值小的servlet,再依次加载其他数值大的servlet.-->
    <load-on-startup>1</load-on-startup>
    <!--设置是否启用异步支持-->
    <async-supported>true</async-supported>
</servlet>
<!--用来定义servlet所对应的URL-->
<servlet-mapping>
    <!--指定servlet的名称-->
    <servlet-name>dispatcher</servlet-name>
    <!--指定servlet所对应的URL-->
    <url-pattern>/</url-pattern>
</servlet-mapping>

在spring-mybatis.xml中,又调用了mybatis-config.xml

<!-- 4   配置sessionfactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <!-- 自动扫描mapping.xml文件 -->
    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>

mybatis-config.xml以及spring-mybatis中,可以调用外部properties文件如jdbc.properties

spring-mybatis.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <!--1 自动扫描 将标注Spring注解的类自动转化Bean-->
    <context:component-scan base-package="com.spring.entity"/>
    <context:component-scan base-package="com.spring.dto"/>

    <!--2 加载数据资源属性文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"/>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${jdbc.maxIdle}"/>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${jdbc.minIdle}"/>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${jdbc.maxWait}"/>
    </bean>

    <!-- 4   配置sessionfactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!-- 5  装配dao接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
        <property name="basePackage" value="com.spring.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!-- 6、声明式事务管理 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 7、注解事务切面 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"/>

    <settings>
        <!-- ☆这个配置使全局的映射器启用或禁用缓存 -->
        <setting name="cacheEnabled" value="true"/>
        <!-- ☆全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- ☆当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载 -->
        <setting name="aggressiveLazyLoading" value="true"/>
        <!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动) -->
        <setting name="multipleResultSetsEnabled" value="true"/>
        <!-- 使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动 -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 允许JDBC支持生成的键。需要适合的驱动。如果设置为true则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby) -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- ☆指定MyBatis如何自动映射列到字段/属性。PARTIAL只会自动映射简单,没有嵌套的结果。FULL会自动映射任意复杂的结果(嵌套的或其他情况) -->
        <setting name="autoMappingBehavior" value="PARTIAL"/>
        <!-- ☆配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新 -->
        <setting name="defaultExecutorType" value="SIMPLE"/>
    </settings>

    <!-- 别名定义 -->
    <typeAliases>
        <!-- 将类名第一个字母变为小写作为别名 -->
        <package name="com.spring.entity"/>
        <package name="com.spring.dto"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/lifecat"/>
                <property name="username" value="root"/>
                <property name="password" value="wangshihao"/>
                <!-- 在任意时间存在的活动(也就是正在使用)连接的数量 -->
                <property name="poolMaximumActiveConnections" value="10"/>
                <!-- 任意时间存在的空闲连接数 -->
                <property name="poolMaximumIdleConnections" value="5"/>
                <!-- 在被强制返回之前,池中连接被检查的时间 -->
                <property name="poolMaximumCheckoutTime" value="20000"/>
                <!-- 这是给连接池一个打印日志状态机会的低层次设置,还有重新尝试获得连接,这些情况下往往需要很长时间(为了避免连接池没有配置时静默失败) -->
                <property name="poolTimeToWait" value="20000"/>
                <!-- 发送到数据的侦测查询,用来验证连接是否正常工作,并且准备接受请求。 -->
                <property name="poolPingQuery" value="NO PING QUERY SET"/>
                <!-- 这是开启或禁用侦测查询。如果开启,你必须用一个合法的SQL语句(最好是很快速的)设置poolPingQuery属性 -->
                <property name="poolPingEnabled" value="false"/>
                <!-- 这是用来配置poolPingQuery多次时间被用一次。这可以被设置匹配标准的数据库连接超时时间,来避免不必要的侦测 -->
                <property name="poolPingConnectionsNotUsedFor" value="0"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--扫描包路径下所有xxMapper.xml文件-->
        <package name="classpath:mapper"/>
    </mappers>

</configuration>

spring-mvc.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 1、配置映射器与适配器 -->
    <mvc:annotation-driven/>

    <!-- 2、视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀和后缀 -->
        <property name="prefix" value="/WEB-INF/jsp"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 3、自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器  -->
    <context:component-scan base-package="com.spring.controller"/>

    <context:component-scan base-package="com.spring.service"/>
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--全局范围内环境参数初始化-->
    <context-param>
        <!--参数名称-->
        <param-name>contextConfigLocation</param-name>
        <!--参数取值-->
        <param-value>classpath:spring/spring-mybatis.xml</param-value>
    </context-param>

    <!--以下配置的加载顺序:先 ServletContext >> context-param >> listener >> filter >> servlet >>  spring-->

    <!--过滤器配置-->
    <!--:编码过滤器-->
    <filter>      <!-- 用来声明filter的相关设定,过滤器可以截取和修改一个Servlet或JSP页面的请求或从一个Servlet或JSP页面发出的响应-->
        <filter-name>encodingFilter</filter-name>     <!--指定filter的名字-->
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!--定义filter的类的名称-->
        <async-supported>true</async-supported>     <!--设置是否启用异步支持-->
        <init-param><!--用来定义参数,若在Servlet可以使用下列方法来获得:String param_name=getServletContext().getInitParamter("param-name里面的值");-->
            <param-name>encoding</param-name>   <!--参数名称-->
            <param-value>UTF-8</param-value> <!--参数值-->
        </init-param>
    </filter>
    <filter-mapping><!--用来定义filter所对应的URL-->
        <filter-name>encodingFilter</filter-name>     <!--指定对应filter的名字-->
        <url-pattern>/ *</url-pattern>       <!--指定filter所对应的URL-->
    </filter-mapping>

    <!--监听器配置-->
    <!--:spring监听器-->
    <listener>        <!--用来设定Listener接口-->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class><!--定义Listener的类名称-->
    </listener>
    <!-- 防止Spring内存溢出监听器  -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!---servlet配置-->
    <!--用来声明一个servlet的数据 -->
    <servlet>
        <!--指定servlet的名称-->
        <servlet-name>dispatcher</servlet-name>
        <!--指定servlet的类名称,这里配置了前端控制器-->
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--用来定义参数,可有多个init-param。在servlet类中通过getInitParamenter(String name)方法访问初始化参数    -->
        <init-param>
            <param-name>contextConfigLocation</param-name>  <!--参数名称-->
            <param-value>classpath:spring/spring-mvc.xml</param-value> <!--参数值-->
        </init-param>
        <!--当值为正数或零时:Servlet容器先加载数值小的servlet,再依次加载其他数值大的servlet.-->
        <load-on-startup>1</load-on-startup>
        <!--设置是否启用异步支持-->
        <async-supported>true</async-supported>
    </servlet>
    <!--用来定义servlet所对应的URL-->
    <servlet-mapping>
        <!--指定servlet的名称-->
        <servlet-name>dispatcher</servlet-name>
        <!--指定servlet所对应的URL-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--会话超时配置(单位为分钟)-->
    <session-config>
        <!--如果某个会话在一定时间未被访问,则服务器可以扔掉以节约内存-->
        <session-timeout>120</session-timeout>
    </session-config>

    <!---MIME类型配置 -->
    <!--设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开-->
    <mime-mapping>
        <!--扩展名名称-->
        <extension>*.ppt</extension>
        <!--MIME格式-->
        <mime-type>application/mspowerpoint</mime-type>
    </mime-mapping>

    <!---欢迎页面配置 -->
    <!--定义首页列单.-->
    <welcome-file-list>
        <!--用来指定首页文件名称.我们可以用<welcome-file>指定几个首页,而服务器会依照设定的顺序来找首页.-->
        <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
    </welcome-file-list>

    <!--配置错误页面-->
    <error-page>  <!--将错误代码(Error Code)或异常(Exception)的种类对应到web应用资源路径.-->
        <!--HTTP Error code,例如: 404403-->
        <error-code>404</error-code>
        <!--用来设置发生错误或异常时要显示的页面-->
        <location>/error.html</location>
    </error-page>

    <error-page>
        <!--设置可能会发生的java异常类型,例如:java.lang.Exception-->
        <exception-type>java.lang.Exception</exception-type>
        <!--用来设置发生错误或异常时要显示的页面-->
        <location>/ExceptionError.html</location>
    </error-page>

</web-app>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章