码迷,mamicode.com
首页 > 移动开发 > 详细

SpringMVC之application-context.xml,了解数据库相关配置

时间:2016-03-23 22:20:43      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:

上一篇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> 

②、重点内容介绍

1、EncryptPropertyPlaceholderConfigurer

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

使用了file前缀引导spring从c盘固定的路径加载数据库连接信息。

刚看到这个类的时候,你也许会有一种似曾相识的感觉,没错,她继承了PropertyPlaceholderConfigurer类,只不过我为她加了一层神秘的色彩(Encrypt嘛),其作用呢,就是为了不直接在项目运行环境中暴露数据库连接信息,比如说数据库用户名、密码、URL等,这样就等于系统多了一层的安全级别,个人觉得还是非常有用的,所以我之前总结了一篇SpringMVC使用隐式jdbc连接信息

标题写的是SpringMVC,同样适用于Spring,那么这里我就不再唠叨了。

2、dataSource

<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>

使用了dbcp的数据库连接池。

DBCP(DataBase connection pool),数据库连接池。是 apache 上的一个 java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要2个包:commons-dbcp.jar,commons-pool.jar由于建立数据库连接是一个非常耗时耗资源的行为,所以通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,用完后再放回去。

  1. destroy-method=”close”的作用就是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.很关键的一个元素。

  2. 关于数据库连接信息URL、username等就不解释了。

  3. 关于数据库连接池信息我到现在还没有搞得很明白,之前也调查了很多次,不见效果,无奈。。。。

  4. testOnBorrow、validationQuery:通过“select 1 from DUAL”查询语句来验证connection的有效性。网上还有很多资源对这块有专业的解释,反正我是没有看得太明白,之前也曾专门调查过这块东西,现在也回想不起来了,以后再碰到的时候再补充进来。

3、sqlSessionFactory

    <!-- 创建SqlSessionFactory,同时指定数据源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
</bean>

sqlSessionFactory对于Spring以及mybatis来说就比较关键了,spring在建立sql连接使都会使用到这个。由于我的不专业性,所以关于更深入的解释,我就不来了,反正对于我来说,这段配置就是为了和数据库连接链接、创建事务管理。

创建sqlSessionFactory时,可能还需要为mybatis配置别名,那么此处改为如下格式:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"/>  
        <property name="dataSource" ref="dataSource" />
    </bean>

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>
    <typeAliases>
       <typeAlias alias=‘Deals‘ type=‘com.honzh.biz.database.entity.Deals‘ />
    </typeAliases>
</configuration>

这样在mapper的xml文件中就可以使用Deals,而不再是com.honzh.biz.database.entity.Deals全名。

<resultMap type="Deals" id="BaseResultMap">

4、transactionManager、tx:annotation-driven

   <!-- 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" />

transactionManager就是为了开启事务。通过tx:annotation-driven就可以直接在方法或者类上加“@transactional”来开启事务回滚。关于这段,我也必须诚实的说,我只停留在会用的基础上。

5、springContextHolder

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

通过spring的IOC机制(依赖注入),配置springcontext的管理器,该类的具体内容见如下:

package com.honzh.common.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * <strong>SpringContextHolder</strong><br>
 * Spring Context Holder<br> 
 * <strong>Create on : 2011-12-31<br></strong>
 * <p>
 * <strong>Copyright (C) Ecointel Software Co.,Ltd.<br></strong>
 * <p>
 * @author peng.shi peng.shi@ecointel.com.cn<br>
 * @version <strong>Ecointel v1.0.0</strong><br>
 */
public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 得到Spring 上下文环境
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }

    /**
     * 通过Spring Bean name 得到Bean 
     * @param name bean 上下文定义名称
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 通过类型得到Bean
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        checkApplicationContext();
        return (T) applicationContext.getBeansOfType(clazz);
    }

    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext未注入,请在application-context.xml中定义SpringContextHolder");
        }
    }

}

如此,我们就可以轻松的通过SpringContextHolder.getBean方法获取对应的bean类,就不再通过new关键字来创建一个类了,当然该类必须有注解标识,比如说@Service、@Component等。

6、MapperScannerConfigurer

        <!-- 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>

该段配置的目的就是扫描mapper接口,也就是你sql语句的地方。当系统启动运行时,spring会加载你的mapper类,然后检查对应的sql语句是否正确,比如字段名是否匹配等等,若不匹配系统自然会报错。另外特别注意的是basePackage的value值一定要正确,我就曾深受其害。

ps:
这里请注意,当mybatis-3.1.1-SNAPSHOT.jar的版本为3.0以上时,这样的配置就可能会引发这样的错误

org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class ‘${driver}’

有同仁解释了一下这个道理,见如下

在spring里使用org.mybatis.spring.mapper.MapperScannerConfigurer 进行自动扫描的时候,设置了sqlSessionFactory 的话,可能会导致PropertyPlaceholderConfigurer失效,也就是用${jdbc.username}这样之类的表达式,将无法获取到properties文件里的内容。 导致这一原因是因为,MapperScannerConigurer实际是在解析加载bean定义阶段的,这个时候要是设置sqlSessionFactory的话,会导致提前初始化一些类,这个时候,PropertyPlaceholderConfigurer还没来得及替换定义中的变量,导致把表达式当作字符串复制了。 但如果不设置sqlSessionFactory 属性的话,就必须要保证sessionFactory在spring中名称一定要是sqlSessionFactory ,否则就无法自动注入。又或者直接定义 MapperFactoryBean ,再或者放弃自动代理接口方式。

那么此时的简单解决办法就是将xml改为如下格式:

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.honzh.biz.database.mapper" />
    </bean>

SpringMVC之application-context.xml,了解数据库相关配置

标签:

原文地址:http://blog.csdn.net/qing_gee/article/details/50965633

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!