Search code examples
javaspringspring-annotations

NoSuchBeanDefinitionException : No bean available in Spring


I am facing a very trivial error and cant figure out why. I have created a simple Student class and a MyConfig class for implementing Spring annotation based configuration. I tried using @Bean & @Component both over my Student class but in both cases I am getting the error :

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'student' available

Below is my code using @Component

Main class:

public class AppSingleton {

    public static void main(String[] args) {
        System.out.println("in AppSingleton");
        ApplicationContext context = new AnnotationConfigApplicationContext("MyConfig.class");
        Student s = context.getBean("student",Student.class);
        s.dispStudents();
    }

}

MyConfig:

@Configuration
@ComponentScan("com.shweta.Singleton")
public class MyConfig {

}

Student :

@Component
public class Student {

    int id ;
    String name;
    
    public Student() {
        System.out.println("Hi in student no arg constructor");
    }
    
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public void dispStudents()
    {
        //System.out.println("id: "+id+", name : "+name+", Book id: "+book.getId()+", Book name: "+book.getName());
        System.out.println("Printing student");
        System.out.println("id: "+id+", name : "+name);
    }
    
}

On running AppSingleton.java, I am getting following exception :

Exception in thread "main"

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'student' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:863)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1160)
at com.shweta.Main.AppSingleton.main(AppSingleton.java:14)

Solution

  • Don't use this :

     ApplicationContext context = new AnnotationConfigApplicationContext("MyConfig.class");
    

    Remove the double quotes as they cause the program to crash

    Instead use this:

     ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);