天天看點

SpringMVC之application-context.xml,了解資料庫相關配置

上一篇SpringMVC之web.xml讓我們了解到配置一個web項目的時候,如何做基礎的DispatcherServlet相關配置,作為SpringMVC上手的第一步,而application-context.xml則讓我們了解到如何将資料庫資訊加載到項目中,包含關鍵的資料庫連接配接資訊、sqlSessionFactory、事務等關鍵因素。

①、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:p="http://www.springframework.org/schema/p"
    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-3.0.xsd  
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <bean class="com.honzh.common.config.EncryptPropertyPlaceholderConfigurer">
         <property name="locations">
            <value>file:C:/properties/ymeng.properties</value>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <!-- Connection Info -->
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}?useUnicode=true&amp;characterEncoding=utf8&amp;" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />

        <!-- Connection Pooling Info -->
        <property name="maxActive" value="${maxActive}" />
        <property name="maxIdle" value="${maxIdle}" />
        <property name="defaultAutoCommit" value="false" />
        <property name="timeBetweenEvictionRunsMillis" value="3600000"/>
        <property name="minEvictableIdleTimeMillis" value="3600000"/>

        <property name="testOnBorrow" value="true" />
        <property name="validationQuery">
            <value>select 1 from DUAL</value>
        </property>
    </bean>

    <!-- 建立SqlSessionFactory,同時指定資料源 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>

        <!-- Mapper接口所在包名,Spring會自動查找其下的Mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.honzh.biz.database.mapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

    <!-- transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 可通過注解控制事務 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="springContextHolder" class="com.honzh.common.spring.SpringContextHolder" />
</beans>