这是一个非常简单的程序,其主类为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();
}
}
预期输出是应该执行samir.readsBook()
上的方法JavaLoader
答案 0 :(得分:4)
您需要为Class
构造函数提供一个AnnotationConfigApplicationContext
实例:
new AnnotationConfigApplicationContext(StudentConfig.class);
请注意,StudentConfig.class
与字符串"StudentConfig.class"
不同。
请注意,AnnotationConfigApplicationContext
也具有字符串构造器(这就是为什么您的代码仍可以编译的原因),但是该字符串被解释为用于自动扫描而不是配置的基本程序包。班级名称。