mybatis配置文件导入外部properties文件

1. 创建一个db.properties文件

2.在db.properties文件中写入相关配置。例如,数据库的配置如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/newhelp
jdbc.username=root
jdbc.password=123

注意:在定义这些变量的时候,尽量避免一些系统变量,会出错的。比如username,这个代表操作系统的用户名。

3.在配置Spring-mybatis的Bean文件时,比如引入头声明,如下所示:

<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">

4.Bean配置文件加入:

<!-- 导入db配置 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:spring/db.properties" />

5.使用我们的配置好的变量,连接数据库:

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

猜你喜欢

转载自blog.csdn.net/qq_38006520/article/details/82951862