为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

梦里花落0921 2021-08-13 16:53:29
我是春天的新手。我创建了一个带有默认构造函数和两个参数的类。我在 bean xml 文件中定义了它。但是当我运行应用程序时,它仍然运行默认构造函数而不是带有参数的构造函数。我在这里找不到我做错了什么。这是代码:构造函数ArgsApp.javapackage 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();    }}组织.javapackage 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 回答

  • 1 回答
  • 0 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信