[英]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.