【发布时间】:2022-10-09 00:07:25
【问题描述】:
我面临一个非常微不足道的错误,无法弄清楚原因。我创建了一个简单的 Student 类和一个 MyConfig 类来实现基于 Spring 注解的配置。我尝试在我的 Student 类上同时使用 @Bean 和 @Component 但在这两种情况下我都收到错误:
线程“主”org.springframework.beans.factory.NoSuchBeanDefinitionException 中的异常:没有名为“学生”的 bean 可用
下面是我使用@Component 的代码
主类:
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 时,我收到以下异常:
线程“主”中的异常
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)
【问题讨论】:
-
使用
new AnnotationConfigApplicationContext(MyConfig.class);而不是new AnnotationConfigApplicationContext("MyConfig.class");
标签: java spring spring-annotations