SpringBoot集成Druid数据源的一些小问题

1、Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

出现这种问题,一般有两种可能:

第一种配置写错了,仔细检查配置。参考配置:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      # mysql 8.0 以下
      # url: jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf8&autoReconnect=true&zeroDateTimeBehavior=convertToNull
      &serverTimezone=Asia/Shanghai
      # driver-class-name: com.mysql.jdbc.Driver
      # mysql 8.0 以上使用
      url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=GMT%2B8&characterEncoding=utf8
        &autoReconnect=true&failOverReadOnly=false
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: root
      # 配置初始化连接池大小(默认0)、最小、最大(默认8)
      initial-size: 5
      # 最小连接池个数——》已经不再使用,配置了也没效果
      min-idle: 2
      # 最大连接池个数
      max-active: 20
      # 配置获取连接等待超时的时间
      max-wait: 60000
      # 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大。 默认为false
      pool-prepared-statements: true
      # 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。
      max-open-prepared-statements: 20
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小和最大生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 300000
      max-evictable-idle-time-millis: 900000
      # 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。
      # 如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。
      validation-query: SELECT 1
      # 申请连接时执行validationQuery检测连接是否有效 默认为true
      test-on-borrow: true
      # 归还连接时执行validationQuery检测连接是否有效 默认为false
      test-on-return: false
      # 申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
      test-while-idle: true
      filter:
        stat:
          # 显示sql
          log-slow-sql: true
          # 显示慢sql 2秒
          slow-sql-millis: 2000

第二种可能,没有将 DataSource 交给Spring管理。添加配置类:

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DruidConfig {

//    绑定配置文件的映射属性
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
}

2、java.lang.ClassNotFoundException: org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType

EmbeddedDatabaseType 是 spring-boot-starter-jdbc 包下的内容,单引入 Druid数据源依赖,会造成 spring-boot-starter-jdbc 包缺失。

解决办法

  引入任意包含spring-boot-starter-jdbc的ORM相关依赖,比如引入mybatis-plus的即可解决,如下:

<dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter</artifactId>
      <version>3.5.1</version>
</dependency>

 

posted @ 2025-11-11 19:11  无虑的小猪  阅读(24)  评论(0)    收藏  举报