通过获取配置文件的方式获取dataSource

筅森魡賤 提交于 2020-02-07 09:39:09

第一步:新建工程  SecondSpring

文件目录结构如下:

第二步: 导入spring相关的jar包,已经 mysql的jar包

过程略...

 

第三步: 新建连接数据库的配置文件

db.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123456

 

第四步:新增spring配置文件

common.xml

<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-2.5.xsd">
    
    <import resource="xmlfolder/app1.xml" />
    <import resource="xmlfolder/innerbean.xml" />
    <import resource="xmlfolder/singleton.xml" />
    <import resource="xmlfolder/annotation.xml" />
    <import resource="xmlfolder/gather.xml" />
    <import resource="xmlfolder/date.xml" />
    <import resource="xmlfolder/db.xml" />
</beans>    

db.xml

<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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
      <!--用于加载db.properties配置文件,否则下面的$ 无法使用 -->
    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>db.properties</value>
        </property>
    </bean>
    
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
</beans>    

 

第五步:  新建测试类

JDBCTest.java

package com.xuzhiwen.spring7;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class JDBCTest {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("common.xml");
        DriverManagerDataSource ds = (DriverManagerDataSource) app.getBean("dataSource");
        System.out.println("url:"+ds.getUrl());
        System.out.println("username:"+ds.getUsername());
        System.out.println("password:"+ds.getPassword());
    }
}

 

第六步:运行结果如下

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!