Spring配置文件中如何使用外部配置文件配置数据库连接

2023-04-25,,

直接在spring的配置文件中applicationContext.xml文件中配置数据库连接也可以,但是有个问题,需要在url后带着使用编码集和指定编码集,出现了如下问题,&这个符号报错……

既然这样只能使用外部配置文件设置一些参数,在spring的配置文件applicationContext.xml中获取,然后配置连接数据库

使用properties配置文件连接数据库,在src下新建jdbc.properties文件,按照自己的数据库名,用户名密码更改下面的配置

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/***?useUnicode=true&characterEncoding=utf8
username=****
password=****

在spring的配置文件applicatiContext.xml中加入(这里是引入配置文件)

<!-- 引入jdbc配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:jdbc.properties</value>
</list>
</property>
</bean>

更改之前的数据库配置,名称和配置文件中的对应上即可

<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="${driverClass}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>

整体如下图:

Spring配置文件中如何使用外部配置文件配置数据库连接的相关教程结束。

《Spring配置文件中如何使用外部配置文件配置数据库连接.doc》

下载本文的Word格式文档,以方便收藏与打印。