Spring框架中使用资源文件配置连接数据库

首先,在你的工程跟目下建立一个资源文件

例如SqlServerDBCON.properties

基本内容如下:

#DriverClass

driverClassName=com.microsoft.jdbc.sqlserver.SQLServerDriver

#数据库连接字符串
url=jdbc\:microsoft\:sqlserver\://localhost\:1433;DataBaseName\=yourdb

#数据库用户名
username=sa

#数据库密码
password=123

spring配置文件 applicationContext.xml

部分内容如下

在配置文件中需要加入命名空间

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation=http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

 <context:property-placeholder location="classpath:SqlServerDBCON.properties" />
  
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="${driverClassName}">
  </property>
  <property name="url" value="${url}"></property>
  <property name="username" value="${username}"></property>
  <property name="password" value="${password}"></property>
 </bean>

 

其实很简单,只要按照上面的步骤,一般没问题,加入名空间前需要导入一个叫common-annotations.jar,在spring2.5的框架中有,如果你已经导入,就不用在重复导入了,配置好直接测试就好了。

你可能感兴趣的:(spring,ssh,Spring读取配置文件)