Org springframework beans factory BeanCreationException: Error creating bean with name

* Spring bean 생성 시, 예외 발생 에러 해결 방법

아아....... 오늘도 붉은 색 에러 창을 마주하게 되네요 하하:-(

어쩔 수 없는 초급 개발자의 운명이랄까요ㅋㅋㅋ...

일단 스크린 샷부터 볼까요?

눈여겨 볼 곳은 파란색 부분과 제가 녹색으로 칠해놓은 부분 인데요

어떤 에러인지 어떻게 해결 할 수 있는지 알아봅시다

Org springframework beans factory BeanCreationException: Error creating bean with name

스크린 샷의 원문을 텍스트로 옮겨 봤습니다

영문을 번역해보니...

105, 2016 10:04:47 오후 org.apache.catalina.core.ApplicationContext log

심각: StandardWrapper.Throwable

org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'proTimetableController': Injection of autowired dependencies failed;nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myspring.gachon.timetable.service.ProTimetableService com.myspring.gachon.timetable.controller.ProTimetableController.ProTimetableServiceImpl; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'proTimetableServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:Could not autowire field: private com.myspring.gachon.timetable.dao.ProTimetableDao com.myspring.gachon.timetable.service.ProTimetableServiceImpl.ProTimetableDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.myspring.gachon.timetable.dao.ProTimetableDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 

Problem

Bean 생성 시 예외가 발생하여 생긴 에러 (파란색으로 색칠된 원문 참고)

현재 가천라인 프로젝트에서는 com.myspring.gachon.timetable.dao.ProTimetableDao를 사용하는데, 

이 bean 객체를 찾지 못해서 발생한 에러 (녹색 진하게 색칠된 원문 참고)

Solution

나의 경우 ProTimetableDaoImpl.java를 확인 해 보니 @repository annotation이 빠져있었다

Org springframework beans factory BeanCreationException: Error creating bean with name
 

깔끔하게 annotation 하나만 추가 해 주어 정상적으로 Dao bean 객체를 autowired 할 수 있게 되었다

Comment

솔직히 C V만 잘해도... 이런 실수는 안할 수 있을 텐데, 이런 annotation 에러는 정말 하지말자!

Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

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:\Users\zouhair\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\TESTER\WEB-INF\classes\com\abc\project\model\dao\InterestRateDAO.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 springframework beans factory BeanCreationException: Error creating bean with name

That's all about how to resolve org.springframework.beans.factory.BeanCreationException: Error creating a bean with the name in Java. As I said, most of the time the clue of the root cause lies in the nested exception. You should always pay attention to the "Caused By" keyword. As I said before, this list is by no means complete and these are just a couple of reasons from numerous others which cause this problem. If you come across any other reasons in your project then please share with us.

Other Java Spring articles you may like to explore

  • Spring HelloWorld example using Dependency Injection (tutorial)
  • Difference between Setter and Constructor Injection in Spring? (answer)
  • Difference between BeanFactory and ApplicationContext in Spring? (answer)
  • How to call stored procedures using the Spring framework in Java? (example)
  • What is the bean scope in the Spring framework? (answer)
  • How to implement LDAP authentication using Spring Security? (example)
  • How to implement RBAC (Role-based access control) using Spring? (tutorial)
  • How to limit the number of user sessions using Spring Security? (solution)
  • 5 Books to Learn Spring Framework (books)
  • How to use JDBC database connection pooling with Spring? (tutorial)

P.S. - If you want to learn how to develop RESTful Web Service using Spring MVC in-depth, I suggest you join these free Spring Framework courses. One of the best courses to learn REST with Spring MVC. 

What is error creating bean with name?

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.

What is org Springframework beans factory BeanCreationException?

Cause: org.springframework.beans.factory.CannotLoadBeanClassException. Spring throws this exception when it can't 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.

How do you fix bean instantiation through factory method failure?

Solution 1 It is necessary to create a new class that extends the abstract class. If the bean factory is attempting to get the bean by using the abstract class name, it can find and associate the implemented class. The exception would then be resolved.

Can not create bean Spring?

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.