Thursday, April 20, 2023

Top 5 Common Spring Bean Exception, Error and Solution [BeanDefinitionStoreException, NoSuchBeanDefinitionException, BeanCreationException]

Hello guys, error handling and troubleshooting is an important skill for Java developers. During development you can get variety of exception and sometime they are quite difficult to solve especially if you have no clue what they are and what causing them. Things can be even more difficult if exception is coming from the framework you are using like Spring Framework or Hibernate, that's why its important to know common error and exception for standard framework like Spring. In this article I will explain what BeanDefinitionStoreException, BeanCreationException, NoSuchBeanDefinitionException and BeanDefinitionOverrideException are, what can cause them and how to fix those problems.


Spring Bean Exceptions and Solutions

Here is a list of common Spring Framework exceptions which are related to Spring beans and how to solve them.

What is Spring BeanDefinitionStoreException?


It is a runtime exception, which means that the compiler will not complain about it, but it can be thrown during runtime. Some other common examples of runtime exceptions are NullPointerException, ArrayIndexOutOfBoundsException and InvalidArgumentException.

Spring BeanDefinitionStoreException also inherits abstract class BeansException which tells us it’s related to Spring beans. Most bean exceptions in Spring are fatal.

As Spring BeanDefinitionStoreException extends FatalBeanException we can learn that it’s an unrecoverable fatal exception.

In short, BeanDefinitionStoreException is an exception thrown by BeanFactory when bean definition is invalid. It can return the problematic bean’s name by calling getBeanName() method.

Now that we know what BeanDefinitionStoreException is, let us proceed and figure out how to deal with this exception and what are the possible causes of it.


How to deal with Spring BeanDefinitionStoreException and what can cause it?

There are several common causes that can cause BeanDefinitionStoreException:

1. Missing maven dependencies
One common way this exception is caused is by missing maven dependencies. But how do we know if BeanDefinitionStoreException was caused by missing maven dependencies?
We can know it when we see that the nested exception is java.lang.NoClassDefFoundError. Example:

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException:
Unexpected exception parsing XML document from class path resource [/WEB-INF/mvc-servlet.xml];
nested exception is java.lang.NoClassDefFoundError:
org/aopalliance/aop/Advice


By the error message above we can see that we’re missing Spring AOP module as a maven dependency. A logical solution and next step would be to just add the missing dependency.

2. Different Spring versions in the classpath
Another common way to cause this exception is to have different Spring versions in the classpath.

3. Using non-existent resource
You also want to check the application.properties resource file. This exception often happens when we’re trying to use a resource that is either not listed in application.properties file or it’s listed, but under a different name.

4. Trying to access a non-existent XML file
Trying to access a non-existent XML file can also lead to this exception. Here is an example:

<import resource="non-existent.xml"/>

Since the XML with that name doesn’t exist, we will get the following error message:

org.springframework.beans.factory.BeanDefinitionStoreException:
IOException parsing XML document from ServletContext resource [/non-existent.xml];
nested exception is java.io.FileNotFoundException:
Could not open ServletContext resource [/non-existent.xml]


We can see which file is missing by inspection of the error message.


What is Spring BeanCreationException?


BeanCreationException is thrown when there is an error in creating a bean from a given bean definition. It inherits all the same exceptions as BeanDefinitionStoreException.

How to deal with Spring BeanCreationException and what can cause it?

1. Not having a no-argument constructor
One of the common reasons for this exception is not including the no-argument constructor in your bean. By default, no-argument constructor will be implicitly created by java if you don’t provide any other constructor, but if you do provide it with a constructor that has parameters, java will not make a no-argument constructor implicitly. 

So be sure that your bean has a no-argument constructor, whether java adds it implicitly or you have to declare it explicitly. You can recognize that this is the cause of your problems if you see NoSuchMethodException in your console. 

Example of a badly constructed bean:

@Component
public class Student implements Person {

    public Student(String email) {
        this.email = email;
    }
}


You can notice in the example above that we didn’t include the no-argument constructor and we have one constructor with parameters so no-argument constructor won’t be created automatically.


2. Trying to instantiate an abstract bean

Another way this error gets caused is if you try to get a bean that has been declared as abstract. Abstract beans can’t get instantiated. You can recognize that this is the case if you see BeanInstantiationException in your console.


3. Configuration referencing a class that doesn’t exist

One common cause of BeanCreationException is your configuration referencing a class that doesn’t exist, so the code will break once the bean of a non-existent class tries to instantiate. If you see a ClassNotFoundException in your console it should point you to this conclusion.

4.  Not having a unique bean definition
This exception can often be caused by defining multiple beans by type so Spring doesn’t know which bean you’re trying to create. When you see NoUniqueBeanDefinitionException you can guess that this is what causes your code to break.

5. Trying to inject a non-existent bean
BeanCreationException can also be caused when trying to inject a bean that simply doesn’t exist. How can we know that this is the case? Simply, we’ll get a NoSuchBeanDefinitionException.   


What is Spring NoSuchBeanDefinitionException?


We’re getting this exception when spring can’t find the definition of a bean that we’re trying to instantiate.


How to deal with Spring NoSuchBeanDefinitionException and what can cause it?

1. Bean with that definition doesn’t exist
The most common reason for this error is trying to get a bean by a name when bean by that name doesn’t exist in the configuration. Example of exception:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No bean named 'school' is defined


From the example above we can see that code tries to instantiate a bean with name ‘school’ and a bean by that name doesn’t exist in configuration.
 

2. Bean definition is not unique
Another possible reason for this exception is not having a unique bean definition. We can recognize it by the NoUniqueBeanDefinitionException that actually extends NoSuchBeanDefinitionException.

Most common way NoUniqueBeanDefinitionException occurs is when we try to autowire a bean defined by type when we have multiple bean definitions of the same type.

How can we avoid this problem?
The solution is very simple, we just need to add @Primary annotation to the bean that we want to have a priority over other beans when autowiring happens.


What is Spring BeanDefinitionOverrideException?


This is an exception that occurs when bean overriding is unsuccessful.


How to deal with Spring BeanDefinitionOverrideException and what can cause it?

This exception is caused by two or more beans having the same name. Since the problem is fairly simple, the solutions are also simple. First solution is to rename one of the conflicting beans if you don’t want to override. But in the case you do want to override you will need to allow bean overriding in BeanFactory.


Conclusion

That's all about the common Error and Exception you can get while working with Spring Framework, particularly while working with Spring Beans. In this article, I’ve described some of the common Spring exceptions related to beans, what causes them and how to solve them. Hopefully it will help you when you encounter one of those exceptions.

Other Spring MVC articles and Tutorials you may like

Thanks a lot for reading this article so far. If you like this Java and Spring Framework tutorial then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note. 

 P. S. - If you are a Spring Boot beginner and want to learn the Spring Boot framework from scratch and look for some of the best online resources, you can also check out these best Spring Boot courses for Java developersThis list contains free Udemy and Pluralsight courses to learn Spring Boot from scratch.  

No comments :

Post a Comment