If you are working with Spring Boot with a Spring Config file (application-config.xml) you may come across NoSuchBeanDefinitionException when you create an object of a bean in your code using the ApplicationContext object getBean() method but the bean is not defined in the Spring config file.
Example:package org.code2care.demo;
public class Employee {
private int empId;
private String empName;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="department" class="org.code2care.demo.Department"></bean>
</beans>
package org.code2care.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-config.xml");
Employee employee = applicationContext.getBean("employee", Employee.class);
}
}
Stacktrace:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException:
No bean named 'employee' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:895)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1319)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1237)
at org.code2care.demo.DemoApplication.main(DemoApplication.java:15)
As you can see I have not defined the bean tag under the application-config.xml file for the class employee, to fix this issue, I will need to create it as well.
<bean name="employee" class="org.code2care.demo.Employee"></bean>

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!