[英]No bean named xxx available
It is a very simple program that has a main class as JavaLoader
, one interface Student
. 这是一个非常简单的程序,它有一个主类作为
JavaLoader
,一个接口是Student
。 Student
is implemented by two classes. Student
由两个班级实施。 I have also made a configuration class. 我也做了一个配置类。 When I instantiate the bean from the main class and call a method on
Samir
. 当我从主类实例化bean并在
Samir
上调用一个方法时。 A NoSuchBeanDefinitionException
is thrown. 抛出
NoSuchBeanDefinitionException
。
Main class ( JavaLoader
): 主类(
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
class: StudentConfig
课程:
package spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("spring")
public class StudentConfig {
}
Samir
class: 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();
}
}
The expected output is that the method samir.readsBook()
on JavaLoader
should be executed 预期的输出是应该执行
JavaLoader
上的方法samir.readsBook()
You need to provide a Class
instance to the AnnotationConfigApplicationContext
constructor: 您需要为
AnnotationConfigApplicationContext
构造函数提供一个Class
实例:
new AnnotationConfigApplicationContext(StudentConfig.class);
note that StudentConfig.class
is not the same as the string "StudentConfig.class"
. 请注意,
StudentConfig.class
与字符串"StudentConfig.class"
。
Note that AnnotationConfigApplicationContext
has a string-constructor as well (that's why your code still compiles), but that string is interpreted as a base package for auto-scanning rather than the configuration class name. 请注意,
AnnotationConfigApplicationContext
也有一个字符串构造函数(这就是您的代码仍然编译的原因),但该字符串被解释为自动扫描的基础包而不是配置类名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.