Fix: SpringFramework BeanDefinitionValidationException: Could not find an init method named


Exception Stacktrace:
2024-02-26T15:26:26.316-06:00  WARN 1434 --- [main] o.s.c.s.ClassPathXmlApplicationContext: 

Exception encountered during context initialization - cancelling refresh attempt: 
org.springframework.beans.factory.BeanCreationException: 

Error creating bean with name 'org.code2care.demo.Employee#0' defined in class path resource [applicationConfig.xml]: 
Could not find an init method named 'cool' on bean with name 'org.code2care.demo.Employee#0'

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'org.code2care.demo.Employee#0' defined in class path resource [applicationConfig.xml]: 
Could not find an init method named 'cool' on bean with name 'org.code2care.demo.Employee#0'

	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522)

You will get the above exception when you have a bean defined in the spring config (applicationContext.xml) file that has a init-method defined, but no corresponding method in the Java bean.

Example: 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">

    <bean name="employee" class="org.code2care.demo.Employee" init-method="initMethod">

    </bean>


</beans>
Employee.java
package org.code2care.demo;

public class Employee {

    private int empId;
    private String empName;
}


Solution:

To fix this issue, you will need to either remove init-method attribute from the bean Employee, or add the initMethod() method in the Employee class.

package org.code2care.demo;

public class Employee {

    private int empId;
    private String empName;

    public void initMethod() {
         //your bean initialization logic
        System.out.println("Employee bean init method called...");
    }
}
BeanDefinitionValidationException- Could not find an init method named

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