Spring_Bean属性注入

33 阅读1分钟

1.创建实体类Car和Person

public class Car {
	private String name;
	private double price;
	public Car() {}
	public Car(String name, double price) {
		this.name = name;
		this.price = price;
	}
	//省略get/set方法
}
	
public class Person {
	private String name;
	private Car car;
	//省略get/set方法
}

2.配置applicationContext.xml文件

<?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">
		<!-- 使用setter方法对car的属性进行注入 -->
		<bean id="mCar" class="com.xxx.xxx.Car">
			<property name="name" value="宝马" />
			<property name="price" value="500000" />
		</bean>
		<bean name="person" class="com.xxx.xxx.Person">
			<property name="name" value="b3a4a" />
			<!-- ref引用其它bean的id或name值 -->
			<property name="car" ref="mCar" />
		</bean>
		
		<!-- 使用构造方法对car的属性进行注入 -->
		<bean id="benzCar" class="com.xxx.xxx.Car">
			<constructor-arg name="name value="奔弛" />
			<constructor-arg name="price" value="1000000" />
		</bean>

	</beans>

3.获取对象实例

@Test
public void test(){
	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		Person person = (Person) applicationContext.getBean("person");
		System.out.println(person.getName() + "  " + person.getCar().getName());
		//Car benzCar = (Car)applicationContext.getBean("benzCar")
}