Spring Boot error message: Failed to configure a DataSource


When I run my application I get the following error:

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 

In my case happened when I removed H2 from my pom.xml

The automatic suggestion of Spring Boot is

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). 

Spring Boot during the initialization was looking for a DataSource to initialize a database but it couldn’t find any in the classpath:

ConfigServletWebServerApplicationContext :  
Exception encountered during context initialization - cancelling refresh attempt:  
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource 

Origin of the problem

In my case (and maybe yours), I’m using @SpringBootApplication

@SpringBootApplication 
public class DemoApplication 

The interface uses another interface @EnableAutoConfiguration . EnableAutoConfiguration according to the documentation: Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need.

When Spring parses all your classes, their imports, their dependencies etc. it try to guess the services that you need in you application. In most of the cases there is some implicit reference in the packages imported that referes to a Database.

In my case a reference to the HikariDataSource is found in the classLoader :

Image.jpeg

… and the DataSourceAutoConfiguration is activated.

Solution

To avoid the issue you can exclude DataSourceAutoConfiguration from the auto configuration.

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class} 

SpringBootApplication allows to pass as parameter filters that won't be called during the parsing of the code:

@SpringBootConfiguration 
@EnableAutoConfiguration 
@ComponentScan(excludeFilters = 
 { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), 
	@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) 
public @interface SpringBootApplication { 

DataSourceAutoConfiguration scans the classLoader to find compatible DataSources to initialize a database.

Image.jpeg



WebApp built by Marco using SpringBoot, Java 16, Mustache, Markdown and Hosted using Jelastic