啟動(dòng)springboot時(shí):Failed to configure a DataSource: 'url' attribute is not specified and no embedded ...

啟動(dòng)springboot時(shí):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

從報(bào)錯(cuò)信息中發(fā)現(xiàn)是 DataSource數(shù)據(jù)源配置有問(wèn)題,找不到url這個(gè)參數(shù)

我使用的hikari數(shù)據(jù)庫(kù)連接池,所以在寫配置的時(shí)候根據(jù)IDE提示配置完了參數(shù)

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

檢查了很多遍,可以肯定并不是語(yǔ)法寫的錯(cuò)誤

網(wǎng)上看了很多帖子,大致就是語(yǔ)法錯(cuò)誤,和繞過(guò)springboot 嵌入的數(shù)據(jù)源配置,這里我查看了springboot相關(guān)文檔

image

在31.1.2中,文檔推薦我們使用HikariCP,因?yàn)镠ikari從速度和穩(wěn)定性上都是比較好的一個(gè)數(shù)據(jù)庫(kù)連接池,所以如果我們依賴了spring-boot-starter-jdbc or spring-boot-starter-data-jpa,我們就自動(dòng)引入了Hikari依賴。

如果我們手動(dòng)配置DataSource,我們就需要按照文檔提供的標(biāo)準(zhǔn)去配置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會(huì)根據(jù) spring.datasource.url自動(dòng)配置到嵌入的database中

所以按照規(guī)范重新配置數(shù)據(jù)源

spring:
  datasource:
    # 新的驅(qū)動(dòng)類需要加&serverTimezone=UTC參數(shù),否則會(huì)報(bào)(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.)錯(cuò)誤
    url: jdbc:mysql://localhost:3306/mitutucue?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    username: root
    password: root
    # 我使用的mysql-connector 包版本為8.0.16,mysql 從某個(gè)版本后拋棄了com.mysql.jdbc.Driver驅(qū)動(dòng)類,新的驅(qū)動(dòng)類為com.mysql.cj.jdbc.Driver
    driver-class-name:com.mysql.cj.jdbc.Driver
#    type: com.zaxxer.hikari.HikariDataSource

# mybatis 配置項(xiàng)
mybatis:
  #注意:一定要對(duì)應(yīng)mapper映射xm
  mapper-locations: classpath:mapper/**/*.xml
  # 注意:對(duì)應(yīng)實(shí)體類的路徑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

啟動(dòng)發(fā)現(xiàn)不會(huì)再報(bào)上述錯(cuò)誤

另外,type屬性可以指定連接池,但是需要我們補(bǔ)全相關(guān)連接池依賴


還有一種解決方式,是完全繞過(guò)springboot內(nèi)置數(shù)據(jù)源配置
在我們的啟動(dòng)類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

這個(gè)需要我們進(jìn)行更詳細(xì)的數(shù)據(jù)源聲明

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

    /**
     * 生成數(shù)據(jù)源.  @Primary 注解聲明為默認(rèn)數(shù)據(jù)源
     */
    @Bean(name = "db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hikari")
    @Primary
    public DataSource testDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 創(chuàng)建 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();
    }

    /**
     * 配置事務(wù)管理
     */
    @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);
    }


}

在配置過(guò)程中還遇到一個(gè)十分坑的地方

image


啟動(dòng)報(bào)錯(cuò)

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

說(shuō) mapper-locations: classpath: mapper/*/.xml 配置有問(wèn)題,困擾了好幾天,后來(lái)嘗試性的把classpath:后的空格去掉,ok了,這個(gè)問(wèn)題簡(jiǎn)直慘無(wú)人道啊,這里也不要嘗試可以ctrl 可以點(diǎn)mapper/*/.xml,會(huì)說(shuō)cannot find declaration to go,包括啟動(dòng)類中的dao包掃描器,@MapperScan(basePackages = "com.**"),也是提示cannot find declaration to go,但實(shí)際是可以掃描包的,目前還不清楚原因,所以很多時(shí)候,我們不要被表象所蒙蔽了眼睛

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容