Org springframework beans factory beancreationexception error creating bean with name

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.

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.

In this post, we will see the possible reasons and fixes for the ‘Error creating bean with name entityManagerFactory defined in class path resource : Invocation of init method failed’ error.

Spring Data JPA Interview Questions and Answers

You may encounter this error if you are using JPA in your application. This error indicates that we have something wrong in the database configuration and the EntityManagerFactory is not getting created. There can be multiple reasons for this exception.

Note – Try to look into the bottom of error stack trace that will help you to figure out the exact root cause of this exception.

Let’s see how to fix the Error creating bean with name entityManagerFactory defined in class path resource : Invocation of init method failed error.

1. Check your database configuration. Make sure you have provided proper database details(check for the database name, username, password, and other configuration). For example, if we provide the wrong database name that doesn’t exist in MySQL DB we will get this error. Also if we pro

spring.datasource.url=jdbc:mysql://localhost:3306/springbootcrudexample
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
server.port = 9091

Note – For Postgres and Oracle database configuration check this post.

2. Make sure you are using @ID annotation with the primary key field in your entity class. For example below code will throw org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ error.

@Entity
public class Student implements Serializable {
    //@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "roll_number")
    private String rollNumber;

    @Column(name = "university")
    private String university;
}

3. If you have defined dialect in application.properties file, make sure you are using the correct dialect.

For example, below will not work and throw the error.

spring.jpa.properties.hibernate.dialect =  org.hibernate.dialect.MySQL9Dialect

The dialect name should org.hibernate.dialect.MySQL8Dialect

4. If you are trying to connect remote databases using some IPs, make sure it is up and running and accessible.

5. If you have an older application(not using Spring Boot and Spring Data JPA) try to add the below maven dependency in pom.xml.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.4.Final</version>
</dependency>

and

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.2.3.Final</version>
</dependency>

6. If you are using Java 9, you may end up with org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ error.

Add the below dependency in your pom.xml.

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

7. You may encounter this exception if you have association mapping between entities. Make sure you are using proper mapping for your entities.

  • One To One unidirectional mapping – See an example here.
  • One To One Bidirectional mapping – See an example here.
  • One To Many unidirectional mapping – See an example here.
  • One To Many Bidirectional mapping – See an example here.
  • One To Many Bidirectional Using Join Table(Third table) – See an example here.
  • Many To one unidirectional mapping – See an example here.
  • Many To Many mapping – See an example here.

8. Go through the error stack trace and try to find out the root cause.

For example, if we have the wrong dialect value configured we can get it in the exception stack trace.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1109) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.1.RELEASE.jar:2.3.1.RELEASE]
at com.netsurfingzone.main.SpringMain.main(SpringMain.java:14) [classes/:na]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.(InFlightMetadataCollectorImpl.java:176) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1224) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1255) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE]
… 17 common frames omitted
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.MySQL9Dialect] as strategy [org.hibernate.dialect.Dialect]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:156) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:239) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:183) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:170) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:164) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:74) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:51) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
… 34 common frames omitted
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.MySQL9Dialect]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:133) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:152) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
… 44 common frames omitted
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.MySQL9Dialect
at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[na:1.8.0_251]
at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_251]
at java.lang.Class.forName0(Native Method) ~[na:1.8.0_251]
at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_251]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:130) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
… 45 common frames omitted

9. If you are using JDK 11 and higher version try to add the below dependency.

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.11</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.2.11</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2.11</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>

Below source code is responsible for this exception.

Error creating bean with name entityManagerFactory defined in class path resource : Invocation of init method failed

Hope this tutorial helps to fix org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource.

Other spring data JPA examples.

  • Spring Data JPA CrudRepository findById()
  • Spring Data findById() Vs getOne()
  • Spring Data JPA JpaRepository getOne()
  • Spring Data CrudRepository saveAll() and findAll().
  • Spring Data CrudRepository existsById()
  • Spring Data JPA delete() vs deleteInBatch()
  • Spring Data JPA deleteAll() Vs deleteAllInBatch()
  • Spring Data JPA JpaRepository deleteAllInBatch()
  • Spring Data JPA deleteInBatch() Example
  • Spring Data JPA JpaRepository saveAndFlush() Example
  • Spring Data JPA CrudRepository count() Example
  • Spring Data JPA CrudRepository delete() and deleteAll()
  • Spring Data JPA CrudRepository deleteById() Example
  • CrudRepository findAllById() Example Using Spring Boot
  • Spring Data CrudRepository save() Method.
  • Sorting in Spring Data JPA using Spring Boot.
  • Spring Data JPA example using spring boot.
  • Spring Data JPA and its benefit.

Содержание

  1. How to fix org.springframework.beans.factory.BeanCreationException: Error creating bean with name X [Java Spring]
  2. How to solve Error creating bean with name X [Java Spring]
  3. spring-beancreationexception
  4. Spring BeanCreationException
  5. 1. Overview
  6. Further reading:
  7. Intro to Inversion of Control and Dependency Injection with Spring
  8. BeanNameAware and BeanFactoryAware Interfaces in Spring
  9. Spring 5 Functional Bean Registration
  10. 2. Cause: org.springframework.beans.factory.NoSuchBeanDefinitionException
  11. Further reading:
  12. Intro to Inversion of Control and Dependency Injection with Spring
  13. BeanNameAware and BeanFactoryAware Interfaces in Spring
  14. Spring 5 Functional Bean Registration
  15. 3. Cause: org.springframework.beans.factory.NoUniqueBeanDefinitionException
  16. 4. Cause: org.springframework.beans.BeanInstantiationException
  17. 4.2. java.lang.InstantiationException
  18. 4.3. java.lang.NoSuchMethodException
  19. 5. Cause: org.springframework.beans.NotWritablePropertyException
  20. 6. Cause: org.springframework.beans.factory.CannotLoadBeanClassException
  21. 7. Children of BeanCreationException
  22. 7.2. The org.springframework.beans.factory.BeanIsAbstractException
  23. 8. Conclusion
  24. 2 Reasons of org.springframework.beans.factory.BeanCreationException: Error creating bean with name [Solution]
  25. 1) No default constructor on Spring Bean
  26. 2) Spring Bean dependent on third party library

How to fix org.springframework.beans.factory.BeanCreationException: Error creating bean with name X [Java Spring]

If you are using the Spring framework in your Java application and getting this error during startup it means Spring is not able to initialize the bean X and add it into its application context, Why? There could be multiple reasons like a typo on the spring bean name. Let’s take a closer look at the stack trace to find out the real reason:

BeanInstantiationException: Could not instantiate bean class [X]: No default constructor found; nested exception is java.lang.NoSuchMethodException: X.()

Here X is the class, which is declared as Spring bean. The error clearly says that the default constructor is not present in class X.

By default, Spring will try to instantiate beans by calling the default or no-argument constructor and if it doesn’t find the default, no-argument constructor then it is not able to initialize the bean and hence it throws the BeanInstantiationException during startup, the real reason is also appended into stack trace as NoSuchMethodException.

If you remember, Java by default adds a default constructor in every class but many programmers don’t know that it only does that if you don’t have any constructor in the class if by any chance you have defined a constructor which takes a parameter, then Java will not add it.

This is also one of the reasons I suggest always add a default constructor in the Java class, no matter whether you have more constructors or not. Java allows constructor overloading and you should take advantage of that.

I also suggest you go through a comprehensive Spring online training course to understand how Spring works, how it instantiates objects, where does it keep the object reference, dependency injection, IOC container, and much more.

If you need a recommendation then I suggest you join one of the courses in this list of best Spring courses for Java developers. It’s one of the most up-to-date resources to learn in Spring and covers Spring 5.0 and Reactive Programming as well.

How to solve Error creating bean with name X [Java Spring]

Now, it depends on how you are instructing Spring to instantiate your bean? If you are using auto-wiring like @Autowired annotation, and you also have a suitable constructor define then just annotated that with @Autwired annotation, as shown below:

Your problem will be solved.

Btw, if you are using XML based configuration then make sure you are using the right constructor on your config.

Also, as per Spring Java documentation, A BeanCrationException is thrown when a BeanFactory encounters an error while attempting to create a bean from bean definition. It doesn’t say anything about the error, that’s why you need to look at the nested exception to find the actual cause.

For example, in this case, the nested error was BeanInstantiationException, which indicates the instantiation of a bean failed.

You should always pay attention to detailed stack trace as It also carries the offending bean class and reason like in this case, it was trying to instantiate bean by invoking default constructor and couldn’t find it.

By looking at the error, you can conclude that whether you need to add a default constructor or Spring is invoking a wrong constructor, which means a missing config somehow.

Sometimes BeanInstantiationException is also throwing in Spring is not able to find the bean class in the classpath. That time you will see either NoClassDefFoundError or ClassNotFoundException as a nested exception in the stack trace.

Источник

spring-beancreationexception

Spring BeanCreationException

1. Overview

In this article, we are discussing the Spring org.springframework.beans.factory.BeanCreationException – this is a very common exception thrown when the BeanFactory creates beans of the bean definitions and encounteres a problem. The article will discuss the most common causes of this exception along with the solution.

Further reading:

Intro to Inversion of Control and Dependency Injection with Spring

A quick introduction to the concepts of Inversion of Control and Dependency Injection, followed by a simple demonstration using the Spring Framework

BeanNameAware and BeanFactoryAware Interfaces in Spring

Have a look at working with the BeanNameAware and BeanFactoryAware interfaces in Spring.

Spring 5 Functional Bean Registration

See how to register beans using the functional approach in Spring 5.

2. Cause: org.springframework.beans.factory.NoSuchBeanDefinitionException

By far the most common cause of the BeanCreationException is Spring trying to inject a bean that doesn’t exist in the context.

For example, BeanA is trying to inject BeanB:

If a BeanB is not found in the context, then the following exception will be thrown (Error Creating Bean):

To diagnose this type of issue – first, make sure the bean is declared:

either in an XML configuration file using the element

or in a Java @Configuration class via the @Bean annotation

or is annotated with: @Component, @Repository, @Service, @Controller and classpath scanning is active for that package

Also check that the configuration files or classes are actually picked up by Spring and loaded into the main context.

Further reading:

Intro to Inversion of Control and Dependency Injection with Spring

A quick introduction to the concepts of Inversion of Control and Dependency Injection, followed by a simple demonstration using the Spring Framework

BeanNameAware and BeanFactoryAware Interfaces in Spring

Have a look at working with the BeanNameAware and BeanFactoryAware interfaces in Spring.

Spring 5 Functional Bean Registration

See how to register beans using the functional approach in Spring 5.

3. Cause: org.springframework.beans.factory.NoUniqueBeanDefinitionException

Another similar cause for the bean creation exception is Spring trying to inject a bean by type – namely by its interface – and finding two or more bean implementing that interface in the context.

For example, BeanB1 and BeanB2 both implement the same interface:

This will lead to the following exception being thrown by the Spring bean factory:

4. Cause: org.springframework.beans.BeanInstantiationException

==== 4.1. Custom Exception

Next in line is a bean that throws an exception during its creation process; a simplified sample to easily exemplify and understand the problem is throwing an exception in the constructor of the bean:

As expected, this will lead to Spring failing fast with the following exception:

4.2. java.lang.InstantiationException

Another possible occurence of the BeanInstantiationException is defining an abstract class as a bean in XML; this has to be in XML, because there is no way to do this in a Java @Configuration file and classpath scanning will ignore the abstract class:

And the XML definition of the bean:

This setup will result in a similar exception:

4.3. java.lang.NoSuchMethodException

If a bean has no default constructor and Spring tries to instantiate it by looking for that constructor, this will result in a runtime exception; for example:

When this bean is picked up by the classpath scanning mechanism, the failure will be:

A similar exception, but harder to diagnose, may occur when the Spring dependencies on the classpath do not have the same version; this kind of version incompatibility may result in a NoSuchMethodException because of API changes. The solution to such a problem is to make sure all Spring libraries have the exact same version in the project.

5. Cause: org.springframework.beans.NotWritablePropertyException

Yet another possiblity is defining a bean – BeanA – with a reference to another bean – BeanB – without having the corresponding setter method in BeanA:

And the Spring XML Configuration:

Again, this can only occur in XML Configuration, because when using Java @Configuration, the compiler will make this issue impossible to reproduce.

Of course, in order to solve this issue, the setter needs to be added for IBeanB:

6. Cause: org.springframework.beans.factory.CannotLoadBeanClassException

This exception is thrown when Spring cannot load the class of the defined bean – this may occur if the Spring XML Configuration contains a bean that simply doesn’t have a corresponding class. For example, if class BeanZ doesn’t exist, the following definition will result in an exception:

The root cause if the ClassNotFoundException and the full exception in this case is:

7. Children of BeanCreationException

==== 7.1. The org.springframework.beans.factory.BeanCurrentlyInCreationException

One of the subclasses of BeanCreationException is the BeanCurrentlyInCreationException; this usually occurs when using constructor injection – for example, in a case of circular dependencies:

Spring will not be able to resolve this kind of wiring scenario and the end result will be:

The full exception is very verbose:

7.2. The org.springframework.beans.factory.BeanIsAbstractException

This instantiation exception may occur when the Bean Factory attempts to retrieve and instantiate a bean which was declared as abstract; for example:

Declared in the XML Configuration as:

Now, if we try to retrieve BeanA from the Spring Context by name – for example when instantiating another bean:

This will result in the following exception:

And the full exception stacktrace:

8. Conclusion

At the end of this article, we should have a clear map to navigate the variety of causes and problems that may lead to a BeanCreationException in Spring, as well as a good grasp on how to fix all of these problems.

The implementation of all exceptions examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.

Источник

2 Reasons of org.springframework.beans.factory.BeanCreationException: Error creating bean with name [Solution]

The Spring framework is one of the most popular frameworks for developing Java applications. Apart from many goodies, it also provides a DI and IOC container that initializes objects and their dependencies and assembles them together. The Java classes created and maintained by Spring are called Spring bean. At the startup, when the Spring framework initializes the system by creating objects and their dependencies depending upon @Autowired annotation or spring configuration XML file, it throws «org.springframework.beans.factory.BeanCreationException: Error creating a bean with name X» error if it is not able to instantiate a particular Spring bean.

There could be numerous reasons why Spring could not able to create a bean with name X, but clue always lies on the detailed stack trace. This error always has some underlying cause e.g. a ClassNotFoundException or a NoClassDefFoundError, which potentially signal a missing JAR file in the classpath.

In short, you should always give a detailed look at the stack trace of your error message and find out the exact cause of «org.springframework.beans.factory.BeanCreationException: Error creating a bean with name» error. The solution would vary accordingly. Btw, If you are curious about how dependency injection works in Spring and how Spring initializes and wires dependencies together, you should read the first few recipes of Spring Recipes book, where you will find a good explanation of IOC and DI containers.

In this article, I’ll share two of the most common reasons for «org.springframework.beans.factory.BeanCreationException: Error creating a bean with name» error in Spring-based Java application and their solutions. These are just based on my limited experience with using Spring framework in core Java application and Java web application if you have come across any other reasons for BeanCreationException in Spring, don’t forget to share with us in comments.

By the way, if you are new to the Spring framework then I also suggest you join a comprehensive and up-to-date course to learn Spring in depth. If you need recommendations, I highly suggest you take a look at these best Spring Framework courses, one of the comprehensive and hands-on resource to learn modern Spring. It’ also the most up-to-date and covers Spring 5. It’s also very affordable and you can buy in just $10 on Udemy sales which happen every now and then.

1) No default constructor on Spring Bean

One of the common mistakes Java programmers make is they forget to define a no-argument constructor in their Spring Bean. If you remember, a spring bean is nothing but a Java class instantiated and managed by Spring. If you also remember, Java compiler adds a default no-argument constructor if you don’t define any, but if you do then it will not insert. It becomes the developer’s responsibility.

Many Java programmer defines a constructor which accepts one or two-argument and forget about the default no-argument constructor, which result in org.springframework.beans.factory.BeanCreationException: Error creating bean with the name at runtime as shown below:

ERROR: org.springframework.web.servlet.DispatcherServlet — Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘InterestRateController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.abc.project.model.service.InterestRateServiceImpl com.abc.project.controller.InterestRateController.InterestRateServ; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘InterestRateServiceImpl’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.abc.project.model.service.InterestRateServiceImpl.setInterestRateDAO(com.abc.project.model.dao.InterestRateDAO); nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘InterestRateDAO’ defined in file [C:Userszouhairworkspace.metadata.pluginsorg.eclipse.wst.server.coretmp1wtpwebappsTESTERWEB-INFclassescomabcprojectmodeldaoInterestRateDAO.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.abc.project.model.dao.InterestRateDAO]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.abc.project.model.dao.InterestRateDAO.()
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)

The most important line in this stack trace is

«No default constructor found; nested exception is java.lang.NoSuchMethodException: com.abc.project.model.dao.InterestRateDAO.()»

which is often overlooked by Java programmers.

2) Spring Bean dependent on third party library

If your Spring bean is using a third party library and that library is not available in the classpath at runtime, Spring will again throw
«org.springframework.beans.factory.BeanCreationException: Error creating a bean with name» error. When you look at the stack trace just look for the «Caused By» keyword, this often gives clues about the real error which is causing the problem. Sometimes this can be a ClassNotFoundException while other times a NoClassDefFoundError.

Here is a code snippet which defines beans in Spring configuration and how one single bean is used as a dependency for several other beans. The bean is created and maintained by the Spring IOC container.

Источник

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Org postgresql util psqlexception ошибка оператор не существует integer character varying
  • Org postgresql util psqlexception error relation does not exist
  • Org postgresql util psqlexception error operator does not exist bigint character varying
  • Org postgresql util psqlexception an i o error occurred while sending to the backend
  • Org openqa selenium webdriverexception unknown error cannot determine loading status

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии