为什么即使提供了参数,spring bean仍运行默认构造函数?

时间:2018-08-27 07:27:32

标签: java spring dependency-injection inversion-of-control spring-bean

我是Spring的新手。我创建了一个带有默认构造函数和两个参数的类。我在bean xml文件中定义了它。但是当我运行该应用程序时,它仍然运行默认的构造函数,而不是带有参数的构造函数。我在这里找不到我在做什么错。这是代码:

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>

1 个答案:

答案 0 :(得分:0)

在使用ClassPathXmlApplicationContext时,将加载目录资源下的beans.xml。如果该文件存在于其他任何地方,将不会被加载