Spring 构造方法注入

在Spring中,一个bean只能为一个构造方法注入!

1、当只有个一个构造方法,且构造方式只有一个参数:

<bean id="user" class="com.clover.bean.User">
<constructor-arg value="boy" />
<property name="name" value="clover" />
<property name="age" value="26"></property>
</bean>


public User(String sex) {
this.sex = sex;
}
这个时候直接注入值即可,不用指定构造方法中参数的类型。

2、当构造方法有两个参数,Constructor-based DI会根据配置文件中代码顺序,为构造方法注入值。

<bean id="user" class="com.clover.bean.User">
<constructor-arg value="boy" />
<constructor-arg value="郑州" />
<property name="name" value="clover" />
<property name="age" value="26"></property>
</bean>


public User(String sex, String addr) {
this.sex = sex;
this.addr = addr;
}
所以,如果把参数的顺序搞错的话,会得到错误的值。如果构造方法的参数类型不一样就会报错。

在<constructor-arg />中指定type(参数类型)、index(文职)以及name(参数属性名)可以解决问题。

<bean id="user" class="com.clover.bean.User">
<constructor-arg name="age" index="1" type="int" value="26" />
<constructor-arg name="sex" index="0" type="java.lang.String" value="boy" />
</bean>


type、index和name在优先级上应该是平行的。不过,name用的时候有需要注意的地方。
Spring官方文档:[quote]Keep in mind that to make this work out of the box your code must be compiled with the debug flag enabled so that Spring can look up the parameter name from the constructor. If you can’t compile your code with debug flag (or don’t want to) you can use @ConstructorProperties JDK annotation to explicitly name your constructor arguments. [/quote]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值