启动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相关文档
在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);
}
}
在配置过程中还遇到一个十分坑的地方
启动报错
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,但实际是可以扫描包的,目前还不清楚原因,所以很多时候,我们不要被表象所蒙蔽了眼睛