7_Spring_使用外部属性配置文件
7_Spring_使用外部属性配置文件
spring容器可以读取.properties属性配置文件,可以将文件中的信息注入给bean
例如,引入Druid数据源,配置连接池信息
1 导入Druid依赖和mysql-connector依赖
com.alibaba druid 1.1.10 mysql mysql-connector-java 8.0.22
2 准备属性配置文件
resources目录下准备一个jdbc.properties属性配置文件
配置文件内容
- jdbc_driver=com.mysql.cj.jdbc.Driver
- jdbc_url=jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
- jdbc_username=root
- jdbc_password=root
applicationContext中添加context名称空间 并读取属性配置文件
配置druid数据源将属性配置文件中的信息注入到连接池中
- <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:c="http://www.springframework.org/schema/c"
- 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"/>
3 DEBUG测试代码
Generated with Mybase Desktop 8.2.13

浙公网安备 33010602011771号