1.当类有含参构造方法,没有空参构造方法的时候,beans的xml文件没有配置constructor-arg会报错

package com.lixv.entity;

public class Hello {
    private String str;

    public Hello(String str) {
        this.str = str;
    }


    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

在这里插入图片描述

2.constructor-arg实现含参构造方法的三种用法

1.通过参数索引

<bean id="hello" class="com.lixv.entity.Hello">
    <constructor-arg index="0" value="hhhhhhhhhhh"/>
</bean>

2.通过参数类型(当参数有多个相同的类型的时候不好用,所以不推荐用)

<bean id="hello" class="com.lixv.entity.Hello">
    <constructor-arg type="java.lang.String" value="hhhhhhhhhhh"/>
</bean>
3.通过参数名字(推荐,够用!)
<bean id="hello" class="com.lixv.entity.Hello">
    <constructor-arg name="str" value="xxxxxxxxxxx"/>-->
</bean>
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐