<!-- 配置bean class: bean的全类名,通过反射的方式在 IOC 的容器中创建 Bean. 所以要求 中必须有无参数的构造器 id:标识容器中的 bean. id 是唯一的 --> <!-- 使用 setter 方法进行属性注入 --> <bean id="helloWorld" class="com.atguigu.spring.beans.HelloWorld"> <property name="userName" value="Spring"></property> </bean> <!-- 使用构造器注入属性值可以指定参数的位置和参数的类型,以区分重载的构造器 --> <bean id="car" class="com.atguigu.spring.beans.Car"> <constructor-arg value="1000" index="0"></constructor-arg> <constructor-arg value="Audi" index="1"></constructor-arg> <constructor-arg value="shanghai" type="java.lang.String"></constructor-arg> </bean>

package com.atguigu.spring.beans;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * @author 国真 * */public class Main { public static void main(String[] args) { /* //创建一个helloWorld 对象 HelloWorld helloWorld = new HelloWorld(); //设置名字 helloWorld.setUserName("spring"); */ //1. 创建 Spring的IOC容器对象 //ApplicationContext 代表 IOC 容器 //ClassPathXmlApplicationContext:是ApplicationContext接口的实现类,该实现类从类路径下来加载xml配置文件 ApplicationContext ctx = new ClassPathXmlApplicationContext("one.xml"); //2. 从IOC容器中获取Bean实例 //利用 id 定位到 IOC 容器中的 Bean HelloWorld helloWorld = (HelloWorld)ctx.getBean("helloWorld"); Car car = (Car)ctx.getBean("car"); Car car1 = (Car) ctx.getBean("car1"); Person person = (Person) ctx.getBean("person"); Person person2 = (Person) ctx.getBean("person2"); //利用类型返回 IOC 容器中的 Bean, 但要求 IOC 容器中必须只能有一个该类型的 Bean// HelloWorld helloWorld = ctx.getBean(HelloWorld.class); //3. 打印名字 helloWorld.hello(); System.out.println(car); System.out.println(car1); System.out.println(person); System.out.println(person2); }}

package com.atguigu.spring.beans;public class Person { private String name; private int age; private Car car; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", car=" + car + "]"; } public Person(String name, int age, Car car) { super(); this.name = name; this.age = age; this.car = car; } public Person() { super(); }}