admin管理员组文章数量:1571372
一、背景
springboot的出现,让项目搭建变得更方便快捷,同时简化掉很多的样板化配置代码,提高开发效率。
通过idea生成springboot项目,启动报错:Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.
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).
通过错误不难看出是因为dataSource的url配置缺失导致,但是新生成的项目并没有使用到jdbc,为什么会报出这个问题呢?
二、分析
其实这就是spring boot最核心的内容:自动配置
由于在生成项目的过程中勾选了mybatis以及mysql,所以pom中引入myBatis的jar包:
spring boot就会默认加载
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration类, 在该类中我们可以看到加载了datasource的相关配置
三、解决
知道问题的原因后,解决方法有两种:
1、配置正确的数据源信息,在application.yml中增加如下内容:
启动项目,成功。
2、在看SpringBootApplication源码的时候发现,其实是有“exclude”属性的,那我们是否可以通过该属性指定排除加载类呢?
答案是肯定的,如下所示:
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
或者
@SpringBootApplication(exclude={DruidDataSourceAutoConfigure.class})
取决于具体的数据源,也可以通过逗号分割,都填上:
@SpringBootApplication(exclude={DruidDataSourceAutoConfigure.class, DataSourceAutoConfiguration.class})
服务启动成功。
另一种方法
前面我们通过exclude语法强制排除掉某个依赖,但是毕竟涉及到代码了,不太友好,需要重新编码,对于spring cloud的很多模块来说,可以再配置文件中去掉某个模块,以nacos为例:
spring:
application:
name: xxx
cloud:
nacos:
discovery:
enabled: true '默认值为true,可不填'
server-addr: 127.0.0.1:8848
只要引入了spring-cloud-starter-alibaba-nacos-discovery-2.2.5.RELEASE.jar,即使不配置nacos信息:
spring:
application:
name: xxx
cloud:
也会默认去127.0.0.1:8848寻找nacos服务器,此时可以通过enabled=false来排除nacos模块,不用重新编码。
或者你可以配置成:
@SpringBootApplication(exclude={ NacosDiscoveryAutoConfiguration.class})
原理
一般某个模块都有一个AutoConfiguration,查看其源码:
@ConditionalOnDiscoveryEnabled
@ConditionalOnNacosDiscoveryEnabled
public class NacosDiscoveryAutoConfiguration {
@ConditionalOnDiscoveryEnabled或@ConditionalOnNacosDiscoveryEnabled分别对应前提条件:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ConditionalOnProperty(value = "spring.cloud.discovery.enabled", matchIfMissing = true)
public @interface ConditionalOnDiscoveryEnabled {
配置项 @ConditionalOnProperty(value = “spring.cloud.discovery.enabled
”, matchIfMissing = true) 就是相应的前提条件
参考:
《springboot启动报错:Failed to configure a DataSource》
版权声明:本文标题:【IDEA】springboot启动报错、异常(排除某个模块):Failed to configure a DataSource(数据库database错误) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1727690167a1125770.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论