Car 類寫入兩個構造器(參數不同)
package com.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;
}
public Car(String brand, String corp, int maxSpeed) {
super();
this.brand = brand;
this.corp = corp;
this.maxSpeed = maxSpeed;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", corp=" + corp + ", price=" + price + ", maxSpeed=" + maxSpeed + "]";
}
}
配置檔案如下
<?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
class :bean 的全類名,通過反射的方式在IOC容器中建立bean,是以要求必須要有無參的構造器
id: 表示容器中唯一的id
-->
<!--通過構造方法配置bean的屬性 -->
<bean id="car" class="com.beans.Car">
<constructor-arg value="Audi" index="0"></constructor-arg>
<constructor-arg value="ShangHai" index="1"></constructor-arg>
<constructor-arg value="30000" index="2"></constructor-arg>
</bean>
<bean id="car2" class="com.beans.Car">
<constructor-arg value="Boma"></constructor-arg>
<constructor-arg value="ChangSha"></constructor-arg>
<constructor-arg value="240"></constructor-arg>
</bean>
</beans>
運作主類
package com.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//1.建立spring的IOC容器對象
//ApplicationContext 代表IOC容器 是 BeanFactory 接口的子接口
// ClassPathXmlApplicationContext: 是 ApplicationContext的實作類,從類路徑下來加載配置檔案
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//2.從IOC容器中擷取bean執行個體
//利用id定位到IOC容器中的bean
Car car=(Car)ctx.getBean("car");
System.out.println(car);
Car car2=(Car)ctx.getBean("car2");
System.out.println(car2);
}
}
運作結果如圖所示,都比對到了第一個構造器。
那麼怎麼讓第二個bean比對到第二個構造器呢?
加一下屬性類型就可以了,如下圖
<bean id="car2" class="com.beans.Car">
<constructor-arg value="Boma"></constructor-arg>
<constructor-arg value="ChangSha"></constructor-arg>
<constructor-arg value="240" type="int"></constructor-arg>
</bean>