Fix: Could not resolve matching constructor on bean class [Spring Boot]


Exception Stack trace:
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;
    }
fix - could not resolve matching constructor on bean class

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap