7、Spring5-IOC容器-Bean管理xml方式-引入外部属性文件

引入外部文件(如数据库配置文件)

1、直接配置数据库信息

(1)配置德鲁伊数据库连接池

(2)引入德鲁伊连接池的 jar 包

<!--直接配置连接池-->
<!-- DruidDataSource dataSource = new DruidDataSource(); -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <!-- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            set方法注入-->
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://localhost:3306/test"></property>
    <property name="username" value="root"></property>
    <property name="password" value="124869"></property>
</bean>

2、通过引入外部属性文件配置数据库连接池

(1)创建外部属性文件,properties格式文件,在文件中写数据库的信息

prop.driverClass=com.mysql.cj.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/test
prop.userName=root
prop.password=124869
#在属性名当前最好加prop用于区分不会冲突

(2)把外部的properties属性文件引入到Spring配置文件中

引入 context 名称空间

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       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/util http://www.springframework.org/schema/util/spring-util.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/util/spring-context.xsd">

(2)在Spring配置文件中使用标签引入外部属性文件

<!--引入外部属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据库连接池-->
<!-- DruidDataSource dataSource = new DruidDataSource(); -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- dataSource.setDriverClassName("com.mysql.jdbc.Driver");
     set方法注入
-->
  <!-- 获取properties文件内容,根据key获取,使用spring表达式获取 -->
  <property name="driverClassName" value="${prop.driverClass}"></property>
  <property name="url" value="${prop.url}"></property>
  <property name="username" value="${prop.userName}"></property>
  <property name="password" value="${prop.password}"></property>
</bean>

 

posted @ 2022-05-31 09:40  卓汶  阅读(25)  评论(0编辑  收藏  举报