栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring配置数据源

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring配置数据源

1.使用Gradle方式引入依赖
	//引入测试依赖
    testCompile 'junit:junit:4.12'
    //引入spring依赖
    implementation 'org.springframework:spring-context:5.1.5.RELEASE'
	//引入mysql依赖
    implementation 'mysql:mysql-connector-java:5.1.24'
	//引入c3p0依赖
    implementation 'c3p0:c3p0:0.9.1.2'
    //引入druid依赖
    implementation 'com.alibaba:druid:1.2.6'
2.创建数据源 2.1手动创建c3p0数据源
	@Test
    // 测试手动创建c3p0数据源
    fun test1(){
        val dataSource = ComboPooledDataSource()
        dataSource.driverClass = "com.mysql.jdbc.Driver"
        dataSource.jdbcUrl = "jdbc:mysql://localhost:3306/Server01"
        dataSource.user = "root"
        dataSource.password = "root"
        val connection = dataSource.connection
        println(connection)
        connection.close()
    }
2.2手动创建druid数据源
	@Test
    // 测试手动创建druid数据源
    fun test2(){
        val dataSource = DruidDataSource()
        dataSource.driverClassName = "com.mysql.jdbc.Driver"
        dataSource.url = "jdbc:mysql://localhost:3306/Server01"
        dataSource.username = "root"
        dataSource.password = "root"
        val connection = dataSource.connection
        println(connection)
        connection.close()
    }
2.3手动创建druid数据源(加载properties配置文件)(c3p0同理)

2.3.1 在resources目录下创建jdbc.properties配置文件

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

2.3.2 读取配置文件

	@Test
    测试手动创建druid数据源(加载properties配置文件)
    fun test3(){
       //读取配置文件
        val rb = ResourceBundle.getBundle("jdbc")
        val driver = rb.getString("jdbc.driver")
        val url = rb.getString("jdbc.url")
        val username = rb.getString("jdbc.username")
        val password = rb.getString("jdbc.password")

        val dataSource = DruidDataSource()
        dataSource.driverClassName = driver
        dataSource.url = url
        dataSource.username = username
        dataSource.password = password
        val connection = dataSource.connection
        println(connection)
        connection.close()
    }
2.4自动创建druid数据源(c3p0同理)

2.4.1 在resources目录下创建applicationContext.xml配置文件




    
    

    
    
        
        
        
        
    

    
    


2.4.4 引入applicationContext配置文件,测试

 	@Test
    // 测试自动创建druid数据源
    fun test4(){
        val app = ClassPathXmlApplicationContext("applicationContext.xml")
        val dataSource = app.getBean("dataSource") as DruidDataSource
        val connection = dataSource.connection
        println(connection)
        connection.close()
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/682900.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号