Fix: NoSuchBeanDefinitionException: No bean named x available (application-config.xml)


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>
Fix NoSuchBeanDefinitionException

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap