Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'employee' defined in class path resource [applicationConfig.xml]:
Could not resolve matching constructor on bean class [org.code2care.demo.Employee]
(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities.
You should also check the consistency of arguments when mixing indexed and named arguments,
especially in case of bean definition inheritance)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:288)
applicationConfig.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">
<bean name="employee" class="org.code2care.demo.Employee">
<constructor-arg ref="department"/>
</bean>
<bean name="department" class="org.code2care.demo.Department"/>
</beans>
package org.code2care.demo;
public class Employee {
private int empId;
private String empName;
private Department department;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
As you can see in the above code, we have the Department class injected into the Employee class using the constructor injection as per applicationConfig.xml file, but there is no constructor defined with this injection in the class Employee, in the above case we have two choices,
1. Change the applicationConfig.xml bean injection to setter (properties) based.
<bean name="employee" class="org.code2care.demo.Employee">
<property name="department" ref="department"/>
</bean>
2. Or, add a constructor with Department in the Employee class.
public Employee(Department department) {
this.department = department;
}

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!