The new Certification Class of Learn Spring Security is out:

>> CHECK OUT THE COURSE

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.

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:

@Component
public class BeanA {

    @Autowired
    private BeanB dependency;
    ...
}

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

Error creating bean with name 'beanA': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private org.baeldung.web.BeanB org.baeldung.web.BeanA.dependency; 
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [org.baeldung.web.BeanB] 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)}

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

  • either in an XML configuration file using the <bean /> 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.

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:

@Component
public class BeanB1 implements IBeanB { ... }
@Component
public class BeanB2 implements IBeanB { ... }

@Component
public class BeanA {

    @Autowired
    private IBeanB dependency;
    ...
}

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

Error creating bean with name 'beanA': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private org.baeldung.web.IBeanB org.baeldung.web.BeanA.b; 
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: 
No qualifying bean of type [org.baeldung.web.IBeanB] is defined: 
expected single matching bean but found 2: beanB1,beanB2

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:

@Component
public class BeanA {

    public BeanA() {
        super();
        throw new NullPointerException();
    }
    ...
}

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

Error creating bean with name 'beanA' defined in file [...BeanA.class]: 
Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [org.baeldung.web.BeanA]: 
Constructor threw exception; 
nested exception is java.lang.NullPointerException

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:

@Component
public abstract class BeanA implements IBeanA { ... }

And the XML definition of the bean:

<bean id="beanA" class="org.baeldung.web.BeanA" />

This setup will result in a similar exception:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'beanA' defined in class path resource [beansInXml.xml]: 
Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [org.baeldung.web.BeanA]: 
Is it an abstract class?; 
nested exception is java.lang.InstantiationException

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:

@Component
public class BeanA implements IBeanA {

    public BeanA(final String name) {
        super();
        System.out.println(name);
    }
}

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

Error creating bean with name 'beanA' defined in file [...BeanA.class]: Instantiation of bean failed; 
nested exception is org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [org.baeldung.web.BeanA]: 
No default constructor found; 
nested exception is java.lang.NoSuchMethodException: org.baeldung.web.BeanA.<init>()

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:

@Component
public class BeanA {
    private IBeanB dependency;
    ...
}
@Component
public class BeanB implements IBeanB { ... }

And the Spring XML Configuration:

<bean id="beanA" class="org.baeldung.web.BeanA">
    <property name="beanB" ref="beanB" />
</bean>

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:

@Component
public class BeanA {
    private IBeanB dependency;

    public void setDependency(final IBeanB dependency) {
        this.dependency = dependency;
    }
}

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:

<bean id="beanZ" class="org.baeldung.web.BeanZ" />

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

nested exception is org.springframework.beans.factory.BeanCreationException: 
...
nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: 
Cannot find class [org.baeldung.web.BeanZ] for bean with name 'beanZ' 
defined in class path resource [beansInXml.xml]; 
nested exception is java.lang.ClassNotFoundException: org.baeldung.web.BeanZ

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:

@Component
public class BeanA implements IBeanA {
    private IBeanB beanB;

    @Autowired
    public BeanA(final IBeanB beanB) {
        super();
        this.beanB = beanB;
    }
}
@Component
public class BeanB implements IBeanB {
    final IBeanA beanA;

    @Autowired
    public BeanB(final IBeanA beanA) {
        super();
        this.beanA = beanA;
    }
}

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

org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: Is there an unresolvable circular reference?

The full exception is very verbose:

org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'beanA' defined in file [...BeanA.class]: 
Unsatisfied dependency expressed through constructor argument with index 0 
of type [org.baeldung.web.IBeanB]: : 
Error creating bean with name 'beanB' defined in file [...BeanB.class]: 
Unsatisfied dependency expressed through constructor argument with index 0 
of type [org.baeldung.web.IBeanA]: : 
Error creating bean with name 'beanA': Requested bean is currently in creation: 
Is there an unresolvable circular reference?; 
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: 
Is there an unresolvable circular reference?; 
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'beanB' defined in file [...BeanB.class]: 
Unsatisfied dependency expressed through constructor argument with index 0 
of type [org.baeldung.web.IBeanA]: : 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: 
Is there an unresolvable circular reference?; 
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'beanA': 
Requested bean is currently in creation: Is there an unresolvable circular reference?

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:

public abstract class BeanA implements IBeanA {
   ...
}

Declared in the XML Configuration as:

<bean id="beanA" abstract="true" class="org.baeldung.web.BeanA" />

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

@Configuration
public class Config {
    @Autowired
    BeanFactory beanFactory;

    @Bean
    public BeanB beanB() {
        beanFactory.getBean("beanA");
        return new BeanB();
    }
}

This will result in the following exception:

org.springframework.beans.factory.BeanIsAbstractException: 
Error creating bean with name 'beanA': Bean definition is abstract

And the full exception stacktrace:

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'beanB' defined in class path resource 
[org/baeldung/spring/config/WebConfig.class]: Instantiation of bean failed; 
nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: 
Factory method 
[public org.baeldung.web.BeanB org.baeldung.spring.config.WebConfig.beanB()] threw exception; 
nested exception is org.springframework.beans.factory.BeanIsAbstractException: 
Error creating bean with name 'beanA': Bean definition is abstract

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.

Go deeper into Spring Security with the course:

>> LEARN SPRING SECURITY

Sort by:   newest | oldest | most voted
Deepak Pandey
Guest

Hi Eugen. I have confusion about the dependency injection. Which type of injection should be used Field Injection,Setter Injection,Constructor Injection. Also when this injection happens after the completion of bean creation. Dependency Injection can be Lazy?. Thanks in Advance

Eugen Paraschiv
Guest

Hey Deepak,
Well, that of course depends on what you’re trying to do, as well as on your personal preference in some cases. If I were to give you some general advice, I’d say go for constructor injection when you can.
Finally, injection and bean creation are indeed separate, but closely related during the container bootstrap process. You can hook into that process afterwards by implementing, for example – InitializingBean.
Hope that helps. Cheers,
Eugen.

Deepak Pandey
Guest
Hey Eugen. Thanks for sharing knowledge. But what i have seen that constructor injection can lead to exception. There is cyclic dependency get created (using pure annotations as in spring 4). Also if code get bit messy don’t look nice rather then using field injection, every time i have to add a new field in a constructor and all look simpler and cleaner if we use field injection . Googled a lot but didn’t get good reply which injection should be used. Please share knowledge on this topic also. Once More thing, Correct me if am wrong Eugen in Spring… Read more »
Eugen Paraschiv
Guest
Hey Deepak, To answer your first question – that’s one of the reasons I said “it depends”. Sometimes constructor injection isn’t easy, because the code wasn’t built with it in mind from the start. Now – that’s a good indication that some design and refactoring work needs to be done to simplify the dependency graph. That’s going to lead to more testable code (which is one of the reasons I prefer constructor injection). But, if you don’t want to do that, field injection is fine. Now, when it comes to wiring, things are broadly the way you describe them, but… Read more »
Ram Kovalan
Guest

i’m getting this error when am running the grails app on STS ..

can anyone help me out ??

ERROR context.GrailsContextLoader – Error executing bootstraps: Error creating bean with name ‘org.grails.activiti.springsecurity.SetAuthenticatedUserIdFilters’: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘processEngine’: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: Lorg/apache/ibatis/session/SqlSessionFactory;

Message: Error creating bean with name ‘org.grails.activiti.springsecurity.SetAuthenticatedUserIdFilters’: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘processEngine’: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: Lorg/apache/ibatis/session/SqlSessionFactory;

Eugen Paraschiv
Guest

Hey Ram,
First – to answer your question – you’re missing the mybatis dependency in your project – which leads to the NoClassDefFoundError there at the end. That’s the root cause of the entire stack.
Then – just as a quick suggestion – StackOverflow is usually a great place to ask these to-the-point questions – you’ll get an answer a lot quicker. Of course feel free to email me the link and I’ll have a look as well. Cheers,
Eugen.

Noorus Khan
Guest

I am getting this error:

root cause
org.springframework.beans.BeanInstantiationException: Failed to instantiate [java.lang.Long]: No default constructor found; nested exception is java.lang.NoSuchMethodException: java.lang.Long.()
org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:107)

Eugen Paraschiv
Guest

Hey Noorus,
The BeanInstantiationException is different from the BeanCreationException (very similar of course, but still different).
Now – in this case, I would need to see the code of course, but I imagine that you’re trying to instantiate a bean incorrectly – probably by having a required long field somewhere. Cheers,
Eugen.

MountainKiddo
Guest

Is there any way to catch any of these exceptions or any exception for that matter, when the IOC is being constructed?

Eugen Paraschiv
Guest

The simple answer is no – if you’re at the point where an exception like these is thrown, catching it isn’t going to help – you need to see what the root cause is and fix that.
Hope that helps. Cheers,
Eugen.

Gunaseelan
Guest

Hello Eugen (@baeldung)! I am getting,
Exception encountered during context initialization – cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0’: Invocation of init method failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.capm.dashboard.service.cache.CacheContainer] for bean with name ‘scopedTarget.cacheContainer’ defined in ServletContext resource [/WEB-INF/springapp-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.capm.dashboard.service.cache.CacheContainer

Eugen Paraschiv
Guest

Hey Gunaseelan,
So, this thread is only covering the most common exceptions – not every possible exception (that would of course be impossible).
In this case, it looks like you’re missing some dependencies on your classpath.
Cheers,
Eugen.

Gunaseelan
Guest

Hello Eugen!
Actually it was working fine for few days.. When I was cleaned the project and ran the code I got this kind of exception.

Eugen Paraschiv
Guest

Sounds good – glad it worked out 🙂
Cheers,
Eugen.

wpDiscuz