这是一个非常简单的程序,具有JavaLoader这个主类,一个接口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 {
}
萨米尔班:
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()