[英]No bean named xxx available
這是一個非常簡單的程序,它有一個主類作為JavaLoader
,一個接口是Student
。 Student
由兩個班級實施。 我也做了一個配置類。 當我從主類實例化bean並在Samir
上調用一個方法時。 拋出NoSuchBeanDefinitionException
。
主類( JavaLoader
):
package spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JavaLoader {
public static void main(String[] args) {
AnnotationConfigApplicationContext appContext = new
AnnotationConfigApplicationContext("StudentConfig.class");
Student samir = (Student) appContext.getBean("samir", Student.class);
System.out.println(samir.readsBook());
}
}
StudentConfig
課程:
package spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("spring")
public class StudentConfig {
}
Samir
班:
package spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
@Component("samir")
public class Samir implements Student{
@Autowired
@Qualifier("history")
Book book;
public Samir(Book book){
this.book = book;
}
public String readsBook(){
return book.readBook();
}
}
預期的輸出是應該執行JavaLoader
上的方法samir.readsBook()
您需要為AnnotationConfigApplicationContext
構造函數提供一個Class
實例:
new AnnotationConfigApplicationContext(StudentConfig.class);
請注意, StudentConfig.class
與字符串"StudentConfig.class"
。
請注意, AnnotationConfigApplicationContext
也有一個字符串構造函數(這就是您的代碼仍然編譯的原因),但該字符串被解釋為自動掃描的基礎包而不是配置類名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.