[英]Spring NoSuchBeanDefinitionException: No Qualifying Bean of Type [@Repository class] available
[英]NoSuchBeanDefinitionException : No bean available in Spring
我面臨一個非常微不足道的錯誤,無法弄清楚原因。 我創建了一個簡單的 Student class 和一個 MyConfig class 來實現基於 Spring 注釋的配置。 我嘗試在我的學生 class 上使用 @Bean 和 @Component 但在這兩種情況下我都收到錯誤:
線程“主”org.springframework.beans.factory.NoSuchBeanDefinitionException 中的異常:沒有名為“學生”的 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 時,出現以下異常:
線程“主”中的異常
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.