NoSuchBeanDefinitionException:Spring 中没有可用的 bean

NoSuchBeanDefinitionException : No bean available in Spring

我遇到了一个非常微不足道的错误,无法弄清楚原因。我创建了一个简单的 Student class 和一个 MyConfig class 来实现基于 Spring 注释的配置。我尝试在我的 Student class 上同时使用 @Bean 和 @Component 但在这两种情况下我都收到错误:

线程“main”中的异常org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为 'student' 的 bean 可用

下面是我使用@Component

的代码

主要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();
    }

}

我的配置:

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

}

学生:

@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);
    }
    
}

在 运行 AppSingleton.java,我收到以下异常:

线程“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)

不要使用这个:

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

删除双引号,因为它们会导致程序崩溃

改用这个:

 ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);