Spring引入外部数据源

spring-dataSource.xml

数据源配置文件

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"
       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 https://www.springframework.org/schema/context/spring-context.xsd">

<!--    引入jdbc.properties,之后可以通过${key}的方式访问value-->
    <context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<!--    创建德鲁伊外部数据源
           经常会用到,以后spring整合mybatis,只要spring中有数据源,mybatis就可以直接用
-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>

    </bean>
</beans>

jdbc.properties

配置数据库的信息:

java 复制代码
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC&useSSL=false
jdbc.username=root
jdbc.password=********

DataSourceTest.java

测试连接数据库:通过IOC容器管理当前的配置的数据源

java 复制代码
package com.zh.spring.test;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.SQLException;

public class DataSourceTest {
    @Test
    public void testDataSource() throws SQLException {
     ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-datasource.xml");
        DruidDataSource dataSource = ioc.getBean(DruidDataSource.class);
        System.out.println(dataSource.getConnection());
    }
}
相关推荐
steven1582 分钟前
第 17 章 组件与配置问题
后端
二炮手亮子5 分钟前
使用云服务+hermes+mino模型 我用微信操控服务器自己编程并部署实操
java·语言模型·ai编程
dkbnull6 分钟前
Spring Boot配置文件敏感信息加密解密
spring boot·后端
她的男孩9 分钟前
安全同事找我要"上周所有登录失败记录",我查完数据库:一条都没有
java·后端·架构
m0_5873830014 分钟前
本地同城无人机作业接单系统源码:架构拆解与抢单调度实现
java·小程序·架构·需求分析
FantanLee17 分钟前
面试级「分布式 ID 设计方案」
java
陈鋆25 分钟前
Spring AI Framework (六:「任务编排 + 成本仪表盘 + 轨迹评估」的 Agent 平台)
spring·ai·ai编程
青春易逝丶28 分钟前
Maven
java·maven
高级程序源30 分钟前
django校企合作实习基地管理系统82506-计算机课程设计、毕业设计
vue.js·后端·python·mysql·django·课程设计·pygame
吠品33 分钟前
纯HTML+ECharts构建交互式数据看板:实现思路与踩坑记录
java·服务器·数据库