Spring error creating bean with name datasource

I have Spring Boot web application. It's centered around RESTful approach. All configuration seems in place but for some reason MainController fails to handle request. It results in 404 error. How ...

I have Spring Boot web application. It’s centered around RESTful approach. All configuration seems in place but for some reason MainController fails to handle request. It results in 404 error. How to fix it?

@Controller
public class MainController {

    @Autowired
    ParserService parserService;

    @RequestMapping(value="/", method= RequestMethod.GET)
    public @ResponseBody String displayStartPage(){
        return "{hello}";
    }
}

Application

@Configuration
@ComponentScan(basePackages = "")
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer{
        public static void main(final String[] args) {
            SpringApplication.run(Application.class, args);
        }

        @Override
        protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
            return application.sources(Application.class);
        }
}

ParserController

@RestController
public class ParserController {

    @Autowired
    private ParserService parserService;

    @Autowired
    private RecordDao recordDao;

 private static final Logger LOG = Logger.getLogger(ParserController.class);

    @RequestMapping(value="/upload", method= RequestMethod.POST)
    public @ResponseBody String fileUploadPage(
   }
}

UPDATE

Seems like MySQL cannot be initialized by Spring….

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; 

nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; 

nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; 

nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; 

nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.

UPDATE2

application.properties

    # Database 
    spring.datasource.driverClassName = com.mysql.jdbc.Driver
    spring.datasource.url = jdbc:mysql://localhost:3306/logparser
    spring.datasource.username = root
    spring.datasource.password = root
    
    spring.jpa.database = MYSQL
    spring.jpa.show-sql = true
    
    # Hibernate
    hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
    hibernate.show_sql: true
    hibernate.hbm2ddl.auto: update
    entitymanager.packagesToScan: /

UPDATE4

Seems lite controllers not responding eventhough @RequestMapping are set. Why might it be?

PS. It occurs when I run Maven’s lifecycle test.
When running in degub mode in IntelliJ there is no error outputted.

UPDATE5

Also I use this DAO as explained in tutorial….

public interface RecordDao extends CrudRepository<Record, Long> {
}

Using MySQL in Spring Boot via Spring Data JPA and Hibernate

UPDATE6

I did changed my application properties. And tried every single combination but it refuses to work. ;(

Maven output:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running IntegrationTest
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.365 sec <<< FAILURE! - in IntegrationTest
saveParsedRecordsToDatabase(IntegrationTest)  Time elapsed: 2.01 sec  <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.

If you are using Spring Boot and getting errors like «Cannot determine embedded database driver class for database type NONE» or «Error creating a bean with name ‘dataSource’ defined in class path resource DataSourceAutoConfiguration,» then you have come to the right place. In this article, we’ll examine different scenarios in which this Spring Boot error comes up and what you can do to solve it. The general reason for this error is Spring Boot’s auto-configuration, which is trying to automatically configure a DataSource for you but doesn’t have enough information. It is automatically trying to create an instance of DataSourceAutoConfiguration bean and it’s failing.

Like other Spring Frameworks errors, the stack trace looks quite messy, something that they could have improved with Spring Boot, but here are these two errors I mentioned above.

Let’s see what the stack trace looks like in general:

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class SpringBootDemo {

  public static void main(String[] args) {
   SpringApplication.runSpringBootDemo.class, args);
  }

}

It is important to keep in mind that these errors can be intimidating if you are completely new to the Spring Framework. In that case, I suggest you go through a comprehensive Spring Boot course like Learn Spring Boot by Dan Vega on Udemy. Now, let’s see some common causes of this error and what you can do to solve this problem.

1) Spring Boot Error Due to Starter Dependency

Some of my friends get this error even if they don’t need a database. The main reason they were getting this error was because of a starter dependency. For example, some of them included spring-boot-starter-data-jpa, which then included hibernate-entitymanager.jar, and they didn’t have additional things need to set that up.

Sometimes, including incorrect Starter POM, can also solve this problem like adding spring-boot-starter-jdbc  instead of spring-boot-starter-data-jpa dependency.

Spring Boot auto-configuration is triggered by JAR dependencies present in the classpath, and if it pulls something you don’t need, then this type of error can occur.

Spring Boot Starter POM Dependency

2) Due to Missing Dependency

Sometimes, you do need a database but you forgot to include the driver JAR file into the classpath, which can also cause this error. For example, you have specified the following properties in the application.properties, Spring Boots configuration file but didn’t include the corresponding MySQL JDBC driver into the classpath

@Configuration
@EnableAutoConfiguration(
exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class SpringBootDemo {

  public static void main(String[] args) {
     SpringApplication.runSpringBootDemo.class, args);
  }

}

In order to solve this error, either you need to include the correct Starter POM dependency or you need to manually add the MySQL JDBC JAR file into the classpath. If you are interested, you can check out this tutorial to learn more about how to connect a Java application to a database using a MySQL database.

3) Due to Missing Configuration in Application.properties

Spring Boot is good at configuring in-memory databases like H2, HSQLDB, Derby, etc., and it can configure them just by adding their JAR files into the classpath, but for others, you need to give Spring Boot additional details like URL, DriverClass name, etc.

You can do that by adding some properties to the application.properties file with the spring.datasource prefix, as shown in the following example:

spring.datasource.url = jdbc:mysql://localhost/abc
spring.datasource.name=testme
spring.datasource.username=xxxx
spring.datasource.password=xxxx
spring.datasource.driver-class-name= com.mysql.jdbc.Driver spring.jpa.database=mysql
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect

This will provide the Spring Boot auto-configuration component to configure the database for you. If you want to learn more about how auto-configuration works in Spring Boot, I suggest you go through a comprehensive Spring Boot course like Spring Boot: Efficient Development, Configuration, and Deployment on Pluralsight, which will also teach you the details behind @EnableAutoConfiguration   by writing your own auto configurations.

Sometimes, excluding DataSourceAutoConfigution can also solve this problem, especially if you don’t need a database. This will prevent Spring Boot from automatically configuring the database and there won’t be any errors. You can disable auto-configuration for certain classes by using the exclude attribute of the @EnableAutoConfiguration annotation of Spring Boot, as shown below:

org.springframework.beans.factory.BeanDefinitionStoreException: 
Factory method [public javax.sql.DataSource 
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$N
onEmbeddedConfiguration.dataSource()] threw exception; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Cannot determine embedded database driver class for database type NONE. 
  If you want an embedded database please put a supported one on the classpath.:

[INFO] org.springframework.beans.factory.BeanCreationException: 
Cannot determine embedded database driver class for database type NONE. 
If you want an embedded database please put a supported one on the classpath.

You can even exclude more than one classes using exclude attribute with @EnableAutoConfiguration as shown below:

spring.datasource.url = jdbc:mysql://localhost/test

spring.datasource.driver-class-name= com.mysql.jdbc.Driver

That’s all for today onhow to solve the «Cannot determine embedded database driver class for database type NONE» or «Error creating a bean with name ‘dataSource’ defined in class path resource DataSourceAutoConfiguration« problem. In most cases, it is because auto-configuration doesn’t have enough details required to configure the database, but sometimes, it’s also the accidental trigger of database auto-configuration, which can be disabled using the exclude attribute of @EnableAutoConfiguration annotation.

Lastly, if you want to learn Spring Boot in depth, here are some useful resources for your learning:

  • Learn Spring Boot

  • Master Java Web Services with Spring Boot

  • Master Hibernate and JPA with Spring Boot in 100 Steps

  • Learn Spring: The Certification Class

Other Java and Spring Boot articles you may like:

  • 5 Spring Boot Features Every Java Developer Should Know (features)
  • Top 5 Free Courses to learn Spring and Spring Boot in 2019 (courses)
  • 5 Course to Master Spring Boot online in 2019 (courses)
  • 10 Things Java Developer should learn in 2019 (goals)
  • 10 Tools Java Developers use in their day-to-day life (tools)
  • 10 Tips to become a better Java developer in 2019 (tips)
  • 3 Best Practices Java Programmers can learn from Spring (best practices)
  • Top 5 Spring Boot Annotations Java Developers should know (annotations)
  • 5 books to learn Spring Boot and Spring Cloud (books)
  • 5 courses to learn Spring Boot in depth (courses)

Thanks for reading this article! If you liked my explanation and solution of this Spring Boot error, then please share with your friends and colleagues. 

The spring boot exception org.springframework.beans.factory.BeanCreationException: Error creating bean with name happens when a problem occurs when the BeanFactory creates a bean. If the BeanFactory encounters an error when creating a bean from either bean definition or auto-configuration, the BeanCreationException will be thrown. The exception Error creating bean with name defined in file happens most of the time in the @Autowired annotation.

If BeanCreationException is found in the spring boot application, the nested exception would reveal the root cause of the exception. There are multiple nested exceptions that trigger BeanCreationException: Error creating bean with name in the spring boot application.

The nested exception will help you to fix BeanCreationException. The following list describes the common root causes that are seen in the nested exception.

NoSuchBeanDefinitionException: No qualifying bean of type

This exception occurs when the bean is not available or defined while auto-wired in another class.

s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘zoo’: Unsatisfied dependency expressed through field ‘lion’; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.yawintutor.Lion’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

If the root cause exception is displayed as No qualifying bean of type then follow the link below to resolve this exception.

NoSuchBeanDefinitionException: No qualifying bean of type

NoSuchBeanDefinitionException: No bean named available

This exception happens when you try to access a bean that is not available or is not defined in the spring boot context.

Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘lion1’ available

If the root cause exception is displayed as No qualifying bean of type then follow the link below to resolve this exception.

NoSuchBeanDefinitionException: No bean named available

BeanCurrentlyInCreationException: Error creating bean with name: Requested bean is currently in creation

This exception happens when two beans are in circular dependences with each other.

s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘department’ defined in file [/SpringBootBean/target/classes/com/yawintutor/Department.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘lion’ defined in file [/SpringBootBean/target/classes/com/yawintutor/Lion.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘tiger’ defined in file [/SpringBootBean/target/classes/com/yawintutor/Tiger.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘lion’: Requested bean is currently in creation: Is there an unresolvable circular reference?

If the root cause exception is displayed as Requested bean is currently in creation then follow the link below to resolve this exception.

BeanCurrentlyInCreationException: Error creating bean with name: Requested bean is currently in creation

NoUniqueBeanDefinitionException: No qualifying bean of type available: expected single matching bean but found

This exception occurs when the bean is auto-wired that matches two or more loaded beans in the spring boot application context.

s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘zoo’: Unsatisfied dependency expressed through field ‘animal’; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type ‘com.yawintutor.Animal’ available: expected single matching bean but found 2: lion,tiger

If the root cause exception is displayed as expected single matching bean but found then follow the link below to resolve this exception.

NoUniqueBeanDefinitionException: No qualifying bean of type available: expected single matching bean but found

BeanInstantiationException: Failed to instantiate: No default constructor found

If the default constructor is not found while auto-wiring the bean, the exception below will be thrown.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘department’ defined in file [SpringBootBean/target/classes/com/yawintutor/Department.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.yawintutor.Department]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.yawintutor.Department.

If the root cause exception is displayed as No default constructor found then follow the link below to resolve this exception.

BeanInstantiationException: Failed to instantiate: No default constructor found

BeanInstantiationException: Failed to instantiate: Constructor threw exception

If the default constructor throws an exception while auto-wiring the bean, the exception below will be thrown.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘department’ defined in file [/SpringBootBean/target/classes/com/yawintutor/Department.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.yawintutor.Department]: Constructor threw exception; nested exception is java.lang.NullPointerException

If the root cause exception is displayed as Constructor threw exception then follow the link below to resolve this exception.

BeanInstantiationException: Failed to instantiate: Constructor threw exception

BeanInstantiationException: Failed to instantiate: Factory method threw exception

If the bean is not available, try to create and load using the abstract class name and bean factory. The beans are not going to instantiate. In this case, the exception below will be thrown.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘animal’ defined in class path resource [com/yawintutor/SpringConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.yawintutor.AbstractAnimal]: Factory method ‘animal’ threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘abstractAnimal’ available

If the root cause exception is displayed as Factory method threw exception then follow the link below to resolve this exception.

BeanInstantiationException: Failed to instantiate: Factory method threw exception

If you find some other type of BeanCreationException, please add it to the comments section, we will provide you with the solution.

When you start your Spring Boot application you can incur in a configuration 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. More often it could happen if you add spring-data in your pom.xml but you don’t access any database.

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) the error was used because I was using the @SpringBootApplication annotation and I added a dependency to Spring Data in the pom.

@SpringBootApplication 
public class DemoApplication 
<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-data-jpa</artifactId> 
</dependency> 

The interface (@SpringBootApplication) uses another interface @EnableAutoConfiguration.

EnableAutoConfiguration according to the documentation is * attempting to guess and configure beans that you are likely to need.*

When Spring parses all your classes, their imports, their dependencies etc. it will try to guess the services that you need in you application and, more prone to error, it will try to configure them.

In most cases there is some implicit reference to a Database in the packages imported.

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

datasource spring source code

… and the DataSourceAutoConfiguration is activated.

Solution

To avoid the issue you can exclude DataSourceAutoConfiguration from the autoconfiguration:

@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 { 

Here the code source of Spring Boot that shows how the framework tries to initialize the database after scanning the classLoader to find compatible DataSources.

DataSourceAutoConfiguration spring source code

Missing configuration

Another possible issue that could cause the error is the missing configuration of the database in your Spring Boot configuration,
check if you have something similar in your application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/your_database 
spring.datasource.username=your_username 
spring.datasource.password=your_password 

If the configuration is not found Spring Boot will fail to create the DataSource Bean used by the DatabaseIntializer.

Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource 

Понравилась статья? Поделить с друзьями:
  • Splinter cell conviction ubisoft game launcher error код ошибки 1
  • Spn 523004 шакман ошибка
  • Splinter cell conviction critical error general protection fault
  • Spring boot mapping error
  • Spiffs error esptool not found esp8266