您的位置:首页 > 编程语言 > Java开发

Spring-2:bean的两种依赖注入方式

2016-07-06 11:05 573 查看
在生成实例对象的时候有两种方式为bean中的成员变量赋值,一种是通过调用setter方法,另一种是利用构造器方法。调用setter方法在上一篇helloworld的实验中已经使用,这种方法属于属性注入。而利用构造器方法对成员赋值属于构造器注入,本文主要说明构造器注入的实现步骤。

首先创建一个类,类名为Car,在该类中定义四个成员变量、一个构造器并重写toString方法:

package com.atguigu.spring.beans;

public class Car {
private String brand;
private String corp;
private double price;
private int maxSpeed;

public Car(String brand, String corp, double price) {
super();
this.brand = brand;
this.corp = corp;
this.price = price;
}

@Override
public String toString() {
return "Car [brand=" + brand + ", corp=" + corp + ", price=" + price
+ ", maxSpeed=" + maxSpeed + "]";
}
}

注意这里构造器只对brand、corp、price三个成员变量赋值。
接下来在applicationConetxt.xml中进行配置,利用  constructor-arg   这个element向构造器传递参数:

<bean id = "car" class="com.atguigu.spring.beans.Car">
<constructor-arg value="aodi" index="0"></constructor-arg>
<constructor-arg value="shanghai" index="1"></constructor-arg>
<constructor-arg value="300000" index="2" type="double"></constructor-arg>
</bean>

这里的value表示参数值,index表示参数的顺序。
最后再main方法中添加:

Car car = (Car) ctx.getBean("car2");
System.out.println(car);打印输出如下:
Car [brand=aodi, corp=shanghai, price=300000.0, maxSpeed=0]

可以看到已经正确的使用构造器来对bean进行注入。

接下来在Car类中再添加一个构造器:

public Car(String brand, String corp, int maxSpeed) {
super();
this.brand = brand;
this.corp = corp;
this.maxSpeed = maxSpeed;
}

这次对brand、corp和maxSpeed赋值。
在applicationContext.xml 中添加配置:

<bean id="car2" class="com.atguigu.spring.beans.Car">
<constructor-arg value="baoma"></constructor-arg>
<constructor-arg value="nanjing"></constructor-arg>
<constructor-arg value="240" type="int"></constructor-arg>
</bean>

这里要说明一下,type 属性用于区分重载的构造方法(区分重载方法的方式有两种:不同的参数类型、不同的参数个数),如果去掉car类的两个bean配置中的type说明,由于240也能赋值给double类型,所以第二个构造方法不会被调用。在这里想对brand、corp和maxSpeed初始化,必须使用type属性说明来让Spring知道该调用哪个构造方法。当然,如果constructor-arg的个数不同也能区分重载方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息