在这之前,我们用JDBC连接数据库的方法有许多:
- 直接通过JDBC硬代码
- 将数据库连接信息配置到properties文件中,再用
ResourceBundle
进行读取配置文件 - 用MyBatis框架的mybatis-config核心配置文件来配置数据库信息
- 用连接池来获取连接对象
- 现在我们可以用Spring容器来配置连接池获取连接对象
只需要将连接池类路径配置到Bean中,再将相应set方法的属性用property标签配置即可,如果对Spring依赖注入不熟悉可以查看我的上一篇文章Spring依赖注入
在此基础上,为了实现properties文件和Spring配置文件解耦,我们需要在spring配置文件中引入context
命名空间:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 引入之后使用以下标签加载配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
配置文件加载后,即可使用EL表达式${key},将配置文件中的key传入以返回value