国王陛下万万岁

导航

 

1.以下是Spring配置连接Mysql的Druid数据源的xml配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.3.12:3306/bankdb"/>
        <property name="username" value="root"/>
        <property name="password" value="abcd2022"/>
    </bean>

</beans>

  

-----------使用properties文件的方式-------

2.我们常用的方法是把用户名,密码等写在一个properties文件里,然后在xml配置中引入properties文件当中的key-value。

Spring为了能够读取properties文件,需要开辟新的命名空间。

applicationContext.xml

注意:下面的xml配置文件当中,结尾带有"context"的就是新增加的命名空间。

总结:

Spring加载properties文件

1)开辟命名空间

2)定义properties文件的位置

<?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: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="jdbc.properties"/>

    <bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.mysql.driver}"/>
        <property name="url" value="${jdbc.mysql.url}"/>
        <property name="username" value="${jdbc.mysql.username}"/>
        <property name="password" value="${jdbc.mysql.password}"/>
    </bean>

    <bean id="bookDao" class="com.oxygen.dao.impl.BookDaoImpl">
        <property name="name" value="${jdbc.mysql.username}"/>
    </bean>

</beans>

  

上面的xml配置文件为了做演示,定义了一个id="bookDao"的bean,会把从properties文件当中读取到的${jdbc.mysql.username}的值注入给BookDao的name属性,用到了setter注入。

 

如果系统环境变量里面有和properties里面定义的变量重名,则properties里面的变量不会被加载,也就是说系统环境变量的优先级会比properties里面的变量优先级高。

为了使用properties里面面的变量,而不是系统环境变量,我们可以对xml配置文件,让系统环境变量不被使用。

<context:property-placeholder location="jdbc.properties" system-properties-mode="NEVER"/>

 

两年多以前的2020年春节期间,没有为读取properties文件开新的命名空间,导致运行时报错。

这个问题困扰了我很久,不断Google才解决,这是两年前那次报错的文章:

Java Spring用properties配置数据库连接池出现错误的处理方法[图]

 

posted on 2022-10-22 18:14  国王陛下万万岁  阅读(155)  评论(0编辑  收藏  举报