1、通过无参构造方法来创建
这个情况下一定要保证类中有无参构造方法。
- 当在类中没有构建有参构造方法时,类中是默认提供无参构造方法;
- 当在类中提供了有参构造方法时,无参构造方法被覆盖,所以要在类中手动创建无参构造方法。
- 类的属性为:
private String name;
private int age;
- 在配置文件中配置的bean的样式为:
<bean id="h1" class="xyz.bryce.pojo.hello1">
<property name="name" value="bryce_1"/>
<property name="age" value="19"/>
</bean>
以这种方式创建对象时依赖于原始类中的set
方法,即需要在类中设置两个属性的set方法:
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
2、通过有参构造方法来创建
通过有参构造方法来创建类的方式有三种:
1. 通过index参数来设置参数值:
index的下标从0开始
<bean id="h1" class="xyz.bryce.pojo.hello1">
<constructor-arg index="0" value="bryce_2"/>
<constructor-arg index="1" value="20"/>
</bean>
2. 通过参数类型来设置参数值:
<bean id="h1" class="xyz.bryce.pojo.hello1">
<constructor-arg type="java.lang.String" value="bryce_4"/>
<constructor-arg type="int" value="22"/>
</bean>
3. 通过参数名字来设置参数值:
<bean id="h1" class="xyz.bryce.pojo.hello1">
<constructor-arg name="name" value="bryce_3"/>
<constructor-arg name="age" value="21"/>
</bean>
注意点:当在bean中只设置了一个属性值时,那么spring调用的就是只有该属性的有参构造器;当bean中设置了类的所有的属性时,spring调用的就是包含所有属性的有参构造器。
例如:
当bean中设置了所有的属性时
<bean id="h1" class="xyz.bryce.pojo.hello1">
<constructor-arg name="name" value="bryce_3"/>
<constructor-arg name="age" value="21"/>
</bean>
这种情况时,spring调用的构造器为:
public hello1(String name, int age) {
this.name = name;
this.age = age;
}
当在bean中只设置了一个属性时
<bean id="h1" class="xyz.bryce.pojo.hello1">
<constructor-arg type="java.lang.String" value="bryce_4"/>
</bean>
此时,spring调用的有参构造器为:
public hello1(String name) {
this.name = name;
}
bean中设置的属性要与有参构造器一一对应。