【发布时间】:2021-06-07 05:43:52
【问题描述】:
我正在尝试使用 Spring 5,当我运行测试应用程序时,它会抛出此异常。我知道如果我们将 @Autowired 用于 Fields 和 Setter 方法,我们需要一个零参数构造函数,因为首先使用零参数构造函数实例化 bean,然后注入依赖 bean。但是,如果构造函数是@Autowired,为什么我们需要一个零参数的构造函数,因为这个构造函数将用于实例化 bean?
is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.spring.hello.Student]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.spring.hello.Student.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
Student.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Student {
private PersonalInfo pI;
@Autowired
public Student (PersonalInfo pI) {
this.pI = pI;
}
}
PersonalInfo.java
@Component
public class PersonalInfo {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private PersonalInfo() {
System.out.println("constructor...");
}
public String printHello() {
return "PersonalInfo...";
}
}
Test.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.hello.Student;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext("/com/spring/resources/applicationContext.xml");
Student bean = (Student) context.getBean("student");
System.out.println(bean);
}
}
ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:annotation-config/>
<bean id="student" class="com.spring.hello.Student">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="personalInfo" class="com.spring.hello.personalInfo">
<!-- collaborators and configuration for this bean go here -->
</bean>
</beans>
编辑
更新测试类后,我得到了
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'student' available.
【问题讨论】:
-
你能分享你的
applicationContext.xml吗?作为旁注;你的域对象不应该是 bean。 -
同意。这只是为了理解:) 更新
标签: java spring spring-boot