上一篇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,了解数据库相关配置的更多相关文章

  1. EBS安装完成后,对数据库相关配置的改动

    EBS安装完成后,对数据库相关配置的改动 1.转为ASM,数据文件,控制文件,redo log,archived log从文件系统转移至ASM 2.禁用resource manager 由于发现系统的 ...

  2. generator.xml文件与相关配置插件

    一,generator.xml配置信息 1 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE ...

  3. 分享知识-快乐自己:SpringMvc中的四种数据源及相关配置(整合快速集成开发)

     数据库连接: jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://39.105.105.186:3306/SpringMybatis?us ...

  4. 我与solr(五)--关于schema.xml中的相关配置的详解

    先把文件的代码贴上来: <?xml version="1.0" encoding="UTF-8" ?> <!-- 版权说明... --> ...

  5. tomcat下context.xml中JNDI数据源配置

    jndi(Java Naming and Directory Interface,Java命名和目录接口)是一组在Java应用中访问命名和目录服务的API.命名服务将名称和对象联系起来,使得我们可以用 ...

  6. Django初探——工程创建以及models数据库相关配置

    Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能. ...

  7. django配置-mysql数据库相关配置

    Django3版本之前的配置 1. Django默认配置的数据库是sqlite 2. 使用mysql数据库需要下载的包 pip3 install PyMySQL 3. Django配置PyMySQL ...

  8. Tomcat 的context.xml

    1. 在tomcat 5.5之前: --------------------------------------------------------------- Context体如今/conf/se ...

  9. Tomcat 的context.xml说明、Context标签讲解

    Tomcat的context.xml说明.Context标签讲解 1. 在tomcat 5.5之前 --------------------------- Context体现在/conf/server ...

随机推荐

  1. cmanformat - 不是命令啦,是个演示文件

    描述 DESCRIPTION cmanformat 是 man pages 格式的演示文件. 由于系统不同会有差异.在 XWindow 下会好些. __________________________ ...

  2. Vue路由模式及监听

    当然详细情况还是看一下vue的官网吧 官网https://router.vuejs.org/zh/   hash模式下(默认) new VueRouter({ mode : ‘hash’, route ...

  3. java_线程优先级

    线程优先级分为三个等级: MAX_PIORITY:10  优先 MIN_PRIORITY:1 NORM_PRIORITY:5  默认 getPriority:获取优先级 setPriority:设置优 ...

  4. B4. Concurrent JVM 锁机制(synchronized)

    [概述] JVM 通过 synchronized 关键字提供锁,用于在线程同步中保证线程安全. [synchronized 实现原理] synchronized 可以用于代码块或者方法中,产生同步代码 ...

  5. 通俗易懂的Redux了解下

    Redux真的让我脑仁疼,感觉有点搞不定他,因为对我而言太抽象了.所以我用通俗易懂地方法去思考Redux,感觉能够理解了. 本文要点: action 配置行为 store.dispatch(actio ...

  6. 笔试算法题(27):判断单向链表是否有环并找出环入口节点 & 判断两棵二元树是否相等

    出题:判断一个单向链表是否有环,如果有环则找到环入口节点: 分析: 第一个问题:使用快慢指针(fast指针一次走两步,slow指针一次走一步,并判断是否到达NULL,如果fast==slow成立,则说 ...

  7. spring data jpa方法命名规则

    关键字 方法命名 sql where字句 And findByNameAndPwd where name= ? and pwd =? Or findByNameOrSex where name= ? ...

  8. C语言学习3

    实现输入错误后重新输入 通过输入指定的行数和列数打印出二维数组对应的任一行任一列的值: #include <stdio.h> void main() { ][] = {{, , , },{ ...

  9. 80-Force Index,强力指标.(2015.7.1)

    Force Index 强力指标 Index,强力指标.(2015.7.1)" title="80-Force Index,强力指标.(2015.7.1)"> 观井 ...

  10. Java中static、final、static final的区别

    final: final可以修饰:属性,方法,类,局部变量(方法中的变量) final修饰的属性的初始化可以在编译期,也可以在运行期,初始化后不能被改变. final修饰的属性跟具体对象有关,在运行期 ...