springboot项目数据库配置类DatabaseConfig实现代码

1:yml配置类

yaml 复制代码
spring:
  datasource:
    name: text
    url: jdbc:mysql://192.168.11.50:3306/dsdd?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

这样启动项目,没有检查到是否连接数据库成功

2:数据库配置类(添加数据库检查)

java 复制代码
package com.example.poi.utils;

/**
 * @Author xu
 * @create 2023/8/22 21
 */
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Configuration
public class DatabaseConfig {

    @Value("${spring.datasource.url}")
    private String dataSourceUrl;

    @Value("${spring.datasource.username}")
    private String dataSourceUsername;

    @Value("${spring.datasource.password}")
    private String dataSourcePassword;

    @Value("${spring.datasource.driver-class-name}")
    private String dataSourceDriverClassName;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(dataSourceUrl);
        dataSource.setUsername(dataSourceUsername);
        dataSource.setPassword(dataSourcePassword);
        dataSource.setDriverClassName(dataSourceDriverClassName);
        testConnection(dataSource); // 调用检查连接方法
        return dataSource;
    }

    private void testConnection(DataSource dataSource) {
        try (Connection connection = dataSource.getConnection()) {
            System.out.println("数据库连接正常!");
        } catch (SQLException e) {
            // 连接异常处理
            //e.printStackTrace();
            throw new RuntimeException("数据库连接异常!");
        }
    }
}

3:或者通过在启动类添加数据库检测

java 复制代码
@SpringBootApplication
public class YourApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class, args);

        // 检查数据库连接是否正常
        try {
            /** 获取DataSource bean,并调用getConnection()方法测试连接*/
            context.getBean(javax.sql.DataSource.class).getConnection();
            System.out.println("数据库连接正常!");
        } catch (Exception e) {
            System.err.println("数据库连接异常:" + e.getMessage());
            // 处理连接异常的逻辑
        }
    }
}
相关推荐
Python私教6 分钟前
Django 6.0 自带 Tasks 到底能不能替代 Celery?跑完 3 组后台任务后我有答案了
后端·python·django
南凉北往13 分钟前
PandasAI连接LLM对MySQL数据库进行数据分析
数据库·mysql·数据分析
回眸不遇18 分钟前
详谈 QT 布局 QLayout::SizeConstraint 和 QSizePolicy 对 QWidget 尺寸的影响
数据库·qt·系统架构
2601_9657984727 分钟前
MTDb Movie & TV Database Script Setup, Caching, and SEO Guide
linux·服务器·数据库·php
zdl68635 分钟前
EasyMarkets:“机器人商业化仍待验证”
数据库·机器人
Freak嵌入式1 小时前
版本混乱 / 依赖缺失?uPyPi:MicroPython 版 PyPI,彻底解决库管理混乱
linux·服务器·数据库·单片机·嵌入式硬件·性能优化·依赖倒置原则
看昭奚恤哭1 小时前
ontainer App】Container App无法从Container Registries 拉取镜像 - 报错 Forbidden
后端·python·flask
Elastic 中国社区官方博客1 小时前
Elastic 和 OpenAI 合作,将前沿智能引入非结构化企业数据
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai
云和恩墨1 小时前
数据库一体机zData X 3.6.0以“性能、成本、韧性、生态”强化数据库基础设施价值主张
数据库
灯澜忆梦1 小时前
【MySQL7】多表查询
数据库·sql