BeanInstantiationException: Failed to instantiate: Constructor threw exception

The spring boot exception org.springframework.beans.BeanInstantiationException: Failed to instantiate: Constructor threw exception occurs when the default constructor in a bean throws exception when the bean is created. The bean is auto-wired using the annotation @Autowired. If the bean throws exception, the bean could not be auto-wired. If the bean triggers an exception from the default constructor method, the exception BeanInstantiationException will be thrown.

The spring boot bean failed to instantiate due to an exception from the constructor. If the spring boot application begins, the bean classes will be instantiated and loaded in the application context. If an error occurs when the bean was instantiated, the org.springframework.beans.BeanInstantiationException exception would be thrown.

The bean object is created using the default bean constructor. If the java class does not have a default constructor, the bean can not be created. The spring boot framework creates an instance of the class using the constructor and assigns values using setter methods.

As the bean is created at the start of the spring boot application, this exception will be thrown at the start of the application. The code written in the constructor should be minimal and no exception should be produced. If an exception happens in the constructor, the bean will not be initiated. The exception will therefore be thrown.



Exception

The exception org.springframework.beans.BeanInstantiationException: Failed to instantiate: Constructor threw exception stack trace would be similar to the one seen below.

2020-12-09 15:08:31.306  WARN 47045 --- [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: 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
2020-12-09 15:08:31.313  INFO 47045 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-12-09 15:08:31.341 ERROR 47045 --- [           main] o.s.boot.SpringApplication               : Application run failed

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
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1318) ~[spring-beans-5.3.1.jar:5.3.1]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1216) ~[spring-beans-5.3.1.jar:5.3.1]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:571) ~[spring-beans-5.3.1.jar:5.3.1]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.1.jar:5.3.1]


Root Cause

When the spring boot application is starting, the Spring boot application loads the beans into the ApplicationContext. Subsequently, the dependent beans are added to produce other types of beans.A bean is created using the default constructor in the class. If an exception occurs in the default constructor, the bean will not be created and loaded in the spring boot application context.



How to reproduce this exception

The spring boot application throws this exception if an exception occurs in the default constructor method of the class. Create a bean class that will allow an exception in the default constructor. If the spring boot application starts loading all the bean classes, the exception “org.springframework.beans.BeanInstantiationException: Failed to instantiate: Constructor threw exception” will be thrown.

package com.yawintutor;

import org.springframework.stereotype.Component;

@Component
public class Department {
	
	public Department() {
		throw new NullPointerException();
	}
}
package com.yawintutor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Employee {
	@Autowired 
	Department department;
	
}

Output

2020-12-09 15:08:31.306  WARN 47045 --- [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: 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
2020-12-09 15:08:31.313  INFO 47045 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-12-09 15:08:31.341 ERROR 47045 --- [           main] o.s.boot.SpringApplication               : Application run failed

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
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1318) ~[spring-beans-5.3.1.jar:5.3.1]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1216) ~[spring-beans-5.3.1.jar:5.3.1]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:571) ~[spring-beans-5.3.1.jar:5.3.1]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:531) ~[spring-beans-5.3.1.jar:5.3.1]


Solution 1

The exception will show the class at which the default constructor throws exception. Identify the class and go through the default constructor code. If any logical bug exists in the code fix the code. This will resolve the exception. The example below will show the default constructor that will not throw any exception.

The error could be a data error or logical error. If it is a data error, the data should be corrected or handled in the code. For example, if a number is divided by zero, an exception will be thrown. The code should handle if the value is zero. The logical error is an error that will be happen due to the bug in the code. The logical error can be fixed by carefully walk through the code.

package com.yawintutor;

import org.springframework.stereotype.Component;

@Component
public class Department {
	
	public Department() {
		boolean flag = false;
		if(flag) {
			throw new NullPointerException();
		}
	}
}
package com.yawintutor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Employee {
	@Autowired 
	Department department;
	
}


Solution 2

If the exception in the default constructor is unknown, handling an exception is tedious. In this case, the default constructor code will be added to the try catch block and the exception will be logged. In the example below the try catch block is applied to the Department Class Default Constructor.

package com.yawintutor;

import org.springframework.stereotype.Component;

@Component
public class Department {
	
	public Department() {
		try {
			throw new NullPointerException();
		} catch(Exception e) {
			System.out.println("Error occurred");
		}
	}
}
package com.yawintutor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Employee {
	@Autowired 
	Department department;
	
}


Solution 3

The code in the default constructor should be moved to a class method. Hence the bean will be created without any error. The code will be executed manually or post constructor in the bean. The bean loads using the empty default constructor. The code will be executed after the bean is created.

In the example below, the constructor code is moved to a class method. The Department bean is created using the empty default constructor. The load method is called manually before executing other code.

package com.yawintutor;

import org.springframework.stereotype.Component;

@Component
public class Department {
	
	public Department() {
	}


	public void load() throws Exception {
		throw new NullPointerException();
	}
}



Leave a Reply