1、创建Car类,Car.java
package spring.beans;
public class Car {
private String brand;
private String corp;
private int price;
private double maxSpeed;
//创建构造器
public Car(String brand,String corp,double 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 + "]";
}
}
注意上面的toString()方法是按如下方式自动生成的:
2、创建applicationContext配置文件:
<?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的属性-->
<!-- 使用构造器注入属性值可以指定参数的位置和参数的类型,以区分重载的构造器 -->
<bean id="car" class="spring.beans.Car">
<constructor-arg value="Audi" index="0"></constructor-arg>
<constructor-arg value="NanJing" index="1"></constructor-arg>
<constructor-arg value="120" type="double"></constructor-arg>
</bean>
</beans>
3、创建主函数Main.java
package spring.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car=ctx.getBean(Car.class);
System.out.println(car);
}
}
4、执行Main.java,效果如下: