在 《spring笔记1---基于spring框架的第一个程序 》一文中,在spring-conf.xml中配置bean时,我们向这个bean传入了一些参数,但是这些参数都是一些简单数据类型,如int、String等,本文将说明如何将一个bean作为一个参数传给另外一个bena,即bean引用其他bean。
在《spring笔记1---基于spring框架的第一个程序 》这篇文章基础上,我们再进行如下修改:
1 新建一个Mobile类,这个类依赖User对象:
package com.gm.spring_test;
public class Mobile {
private User user; // 手机使用者
private String model; // 手机型号
private float price; // 手机价格
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
2 修改spring-conf.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">
<bean id="User" class="com.gm.spring_test.User">
<property name="age" value="20"></property>
<property name="name" value="jayjay"></property>
</bean>
<bean id="Mobile" class="com.gm.spring_test.Mobile">
<property name="price" value="2999.99"></property>
<property name="model" value="iphoneX"></property>
<property name="user">
<ref bean="User"/>
</property>
</bean>
</beans>
3 使用bean:
ApplicationContext context = new ClassPathXmlApplicationContext("spring-conf.xml");
Mobile mobile = (Mobile) context.getBean("Mobile");
System.out.println(mobile.getUser());