Java 没有名为xxx的bean可用
这是一个非常简单的程序,它有一个主类Java 没有名为xxx的bean可用,java,spring,Java,Spring,这是一个非常简单的程序,它有一个主类JavaLoader,一个接口Student学生由两个类实现。 我还创建了一个配置类。当我从主类实例化bean并调用Samir上的方法时。将引发NoSuchBeanDefinitionException 主类(JavaLoader): StudentConfigclass: package spring; import org.springframework.context.annotation.ComponentScan; import org.sprin
JavaLoader
,一个接口Student
<代码>学生由两个类实现。
我还创建了一个配置类。当我从主类实例化bean并调用Samir
上的方法时。将引发NoSuchBeanDefinitionException
主类(JavaLoader
):
StudentConfig
class:
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();
}
}
Samir
class:
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()
,您需要向注释配置应用程序上下文
构造函数提供一个类
实例:
new AnnotationConfigApplicationContext(StudentConfig.class);
请注意,StudentConfig.class
与字符串“StudentConfig.class”
不同
请注意,
AnnotationConfigApplicationContext
也有一个字符串构造函数(这就是代码仍然可以编译的原因),但该字符串被解释为用于自动扫描的基本包,而不是配置类名 更重要的是,String
constructor使用包名,因此它也可以是newannotationconfigapplicationcontext(“spring”)
@Alex,现在您的答案似乎还可以。