Search code examples
javaspringdependency-injectioninversion-of-controlspring-bean

Why does spring beans runs default constructors even when parameters are provided?


I am new to Spring. I created a class with default constructor and two arguments. I defined it in bean xml file. But still when I run the application, it runs the default constructor instead of the one with parameters. I could not find what am I doing wrong here. Here is the code:

ConstructorArgsApp.java

package com.kirancyrusken.springDemo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ConstructorArgsApp {

    public static void main(String[] args) {
            //1. Create ApplicationContext
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-cp.xml");

            //2 Create the bean
        Organization org = (Organization) ctx.getBean("myorg");

            //3. invoke the company slogan the bean
        org.corporateSlogan();

        System.out.println(org);

            //4. Close the application Context (container)
        ((ClassPathXmlApplicationContext) ctx).close();
    }
}

Organization.java

package com.kirancyrusken.springDemo;

public class Organization {

    private String companyName;
    private int yearOfIncorporation;

    public Organization() {
    }

    public Organization(String companyName, int yearOfIncorporation) {
        this.companyName = companyName;
        this.yearOfIncorporation = yearOfIncorporation;
    }


    public void corporateSlogan() {
        String slogan = "We build the ultimate driving machines";
        System.out.println(slogan);
    }


    @Override
    public String toString() {
        return "Organization [companyName=" + companyName + ", yearOfIncorporation=" + yearOfIncorporation + "]";
    }

}

beans-cp.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 id="myorg" 
    class="com.kirancyrusken.springDemo.Organization">
    <constructor-arg value="BMW"></constructor-arg>
    <constructor-arg value="1929"></constructor-arg>
</bean>


Solution

  • While using ClassPathXmlApplicationContext, beans.xml under the directory resources are loaded. If the file is present anywhere else, it will not be loaded