启动springboot时:Failed to configure a DataSource: 'url' attribute is not specified and no embedded ...

启动springboot时:Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

 :: Spring Boot ::        (v2.1.4.RELEASE)

2019-05-13 14:49:18.295  INFO 25184 --- [  restartedMain] m.s.w.MitutucuteSpringbootWebApplication : Starting MitutucuteSpringbootWebApplication on YUN4JEW6WE93XLS with PID 25184 (D:\JavaWorkSpase\mitutucute-springboot\web\mitutucute-springboot-web\target\classes started by Administrator in D:\JavaWorkSpase\mitutucute-springboot)
2019-05-13 14:49:18.296  INFO 25184 --- [  restartedMain] m.s.w.MitutucuteSpringbootWebApplication : No active profile set, falling back to default profiles: default
2019-05-13 14:49:18.413  INFO 25184 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2019-05-13 14:49:18.413  INFO 25184 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2019-05-13 14:49:20.673  WARN 25184 --- [  restartedMain] t.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in '[com.xxx.xxx.springboot.web]' package. Please check your configuration.
2019-05-13 14:49:20.791  INFO 25184 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2019-05-13 14:49:20.796  INFO 25184 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-05-13 14:49:20.845  INFO 25184 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 22ms. Found 0 repository interfaces.
2019-05-13 14:49:21.514  INFO 25184 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d2de0663] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-05-13 14:49:22.157  INFO 25184 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-05-13 14:49:22.194  INFO 25184 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-13 14:49:22.194  INFO 25184 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.17]
2019-05-13 14:49:22.486  INFO 25184 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-13 14:49:22.486  INFO 25184 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4073 ms
2019-05-13 14:49:22.742  WARN 25184 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'serviceDemo': Unsatisfied dependency expressed through field 'demoDao'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoDao' defined in file [D:\JavaWorkSpase\mitutucute-springboot\dal\mitutucute-springboot-dao\target\classes\com\xxx\xxx\springboot\dao\DemoDao.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [tk/mybatis/mapper/autoconfigure/MapperAutoConfiguration.class]: Unsatisfied dependency expressed through method 'sqlSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
2019-05-13 14:49:22.746  INFO 25184 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-05-13 14:49:22.776  INFO 25184 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-13 14:49:22.786 ERROR 25184 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

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

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).


Process finished with exit code 0

从报错信息中发现是 DataSource数据源配置有问题,找不到url这个参数

我使用的hikari数据库连接池,所以在写配置的时候根据IDE提示配置完了参数

datasource:
  hikari:
    jdbc-url: jdbc:mysql://localhost:3306/mitutucue?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
    read-only: false
    connection-timeout: 30000
    idle-timeout: 600000
    max-lifetime: 180000
    maximum-pool-size: 15

检查了很多遍,可以肯定并不是语法写的错误

网上看了很多帖子,大致就是语法错误,和绕过springboot 嵌入的数据源配置,这里我查看了springboot相关文档

image

在31.1.2中,文档推荐我们使用HikariCP,因为Hikari从速度和稳定性上都是比较好的一个数据库连接池,所以如果我们依赖了spring-boot-starter-jdbc or spring-boot-starter-data-jpa,我们就自动引入了Hikari依赖。

如果我们手动配置DataSource,我们就需要按照文档提供的标准去配置datasource

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

pringboot会根据 spring.datasource.url自动配置到嵌入的database中

所以按照规范重新配置数据源

spring:
  datasource:
    # 新的驱动类需要加&serverTimezone=UTC参数,否则会报(Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.)错误
    url: jdbc:mysql://localhost:3306/mitutucue?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: root
    # 我使用的mysql-connector 包版本为8.0.16,mysql 从某个版本后抛弃了com.mysql.jdbc.Driver驱动类,新的驱动类为com.mysql.cj.jdbc.Driver
    driver-class-name:com.mysql.cj.jdbc.Driver
#    type: com.zaxxer.hikari.HikariDataSource

# mybatis 配置项
mybatis:
  #注意:一定要对应mapper映射xm
  mapper-locations: classpath:mapper/**/*.xml
  # 注意:对应实体类的路径com.xxx.xxx.springboot.dal.model
  type-aliases-package: com.xxx.xxx.springboot.dal.model
  #  config-location: classpath: spring-datasource.xml
  configuration:
    map-underscore-to-camel-case: true

启动发现不会再报上述错误

另外,type属性可以指定连接池,但是需要我们补全相关连接池依赖


还有一种解决方式,是完全绕过springboot内置数据源配置
在我们的启动类Application 上声明@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}),但是这样我们需要做完整的sqlSesson的声明,

Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    at org.springframework.util.Assert.notNull(Assert.java:198) ~[spring-core-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.mybatis.spring.support.SqlSessionDaoSupport.checkDaoConfig(SqlSessionDaoSupport.java:123) ~[mybatis-spring-2.0.1.jar:2.0.1]
    at org.mybatis.spring.mapper.MapperFactoryBean.checkDaoConfig(MapperFactoryBean.java:73) ~[mybatis-spring-2.0.1.jar:2.0.1]
    at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44) ~[spring-tx-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 34 common frames omitted

这个需要我们进行更详细的数据源声明

@Configuration
@MapperScan(basePackages = {"com.***.dao"})
public class DataSource1Config {

    /**
     * 生成数据源.  @Primary 注解声明为默认数据源
     */
    @Bean(name = "db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    @Primary
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 创建 SqlSessionFactory
     */
    @Bean(name = "db1SqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/**/*.xml"));
        return bean.getObject();
    }

    /**
     * 配置事务管理
     */
    @Bean(name = "db1TransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}

在配置过程中还遇到一个十分坑的地方

image


启动报错

Caused by: org.yaml.snakeyaml.scanner.ScannerException: mapping values are not allowed here
 in 'reader', line 32, column 30:
      mapper-locations: classpath: mapper/**/*.xml

说 mapper-locations: classpath: mapper/*/.xml 配置有问题,困扰了好几天,后来尝试性的把classpath:后的空格去掉,ok了,这个问题简直惨无人道啊,这里也不要尝试可以ctrl 可以点mapper/*/.xml,会说cannot find declaration to go,包括启动类中的dao包扫描器,@MapperScan(basePackages = "com.**"),也是提示cannot find declaration to go,但实际是可以扫描包的,目前还不清楚原因,所以很多时候,我们不要被表象所蒙蔽了眼睛

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 210,978评论 6 490
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 89,954评论 2 384
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,623评论 0 345
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,324评论 1 282
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,390评论 5 384
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,741评论 1 289
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,892评论 3 405
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,655评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,104评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,451评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,569评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,254评论 4 328
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,834评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,725评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,950评论 1 264
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,260评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,446评论 2 348