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

    ②、重点内容介绍

    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>
    
  • 相关阅读:
    Centos 7.3 配置Xmanager XDMCP
    xstart使用方法
    Linux下安装xwindow图形界面
    使用Xftp连接Centos 6.6服务器详细图文教程
    linux远程管理器
    xftp的使用教程
    CentOS 7 关闭图形界面
    Java反射机制
    java反射的性能问题
    Java 虚拟机面试题全面解析(干货)
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7156451.html
Copyright © 2020-2023  润新知