我刚刚开始学习Spring并试图制作一个基本的Spring程序,但我无法解决这个错误。以下是代码:
Student.java
@Component
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
配置类
@Configuration
@ComponentScan("springfirst1")
public class ConfigClass {
public Student getStudent(){
return new Student();
}
}
主要类
public class SpringFirst1 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext("ConfigClass.class");
Student s1 = context.getBean(Student.class);
s1.setName("Adam");
System.out.println(s1.getName());
}
}
错误:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [springfirst1.Student] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:318)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:985)
at springfirst1.SpringFirst1.main(SpringFirst1.java:13)
答案 0 :(得分:3)
ApplicationContext
参数中的以下更改可以解决此问题。
主要类
public class SpringFirst1 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ConfigClass.class);
Student s1 = context.getBean(Student.class);
s1.setName("Gaurav");
System.out.println(s1.getName());
}
答案 1 :(得分:0)
public Student getStudent(){
return new Student();
}
如果你把@Component放在你的上面,这是没有必要的:
如果你想使用java配置,你必须将@Bean放在它上面:
@Bean
public Student getStudent(){
return new Student();
}
编辑:检查Arun回答:-)