7_Spring_使用外部属性配置文件

7_Spring_使用外部属性配置文件

spring容器可以读取.properties属性配置文件,可以将文件中的信息注入给bean

例如,引入Druid数据源,配置连接池信息

1  导入Druid依赖和mysql-connector依赖

  1. com.alibaba
  2. druid
  3. 1.1.10
  4. mysql
  5. mysql-connector-java
  6. 8.0.22

2 准备属性配置文件

resources目录下准备一个jdbc.properties属性配置文件

image
配置文件内容

  1. jdbc_driver=com.mysql.cj.jdbc.Driver
  2. jdbc_url=jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
  3. jdbc_username=root
  4. jdbc_password=root

applicationContext中添加context名称空间 并读取属性配置文件

配置druid数据源将属性配置文件中的信息注入到连接池中

  1. <beans xmlns="http://www.springframework.org/schema/beans"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:c="http://www.springframework.org/schema/c"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context.xsd
  10. ">
  11. <context:property-placeholder location="classpath:jdbc.properties"/>

3 DEBUG测试代码

image


Generated with Mybase Desktop 8.2.13

posted @ 2023-07-30 12:36  AidenDong  阅读(41)  评论(0)    收藏  举报