zoukankan      html  css  js  c++  java
  • 通过获取配置文件的方式获取dataSource

    第一步:新建工程  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());
        }
    }

    第六步:运行结果如下

  • 相关阅读:
    十进制数转换
    桶排序
    快速排序
    单词倒排
    (c++) string b; cin>>b; int i=strlen(b); 报错的原因。
    n的阶乘(1<n<10000)(结果超大……)
    2020软件工程最后一次作业
    2020软件工程第四次作业
    2020软件工程第三次作业
    2020软件工程第二次作业
  • 原文地址:https://www.cnblogs.com/beibidewomen/p/7390800.html
Copyright © 2011-2022 走看看