spring笔记2---bean引用其他bean

在 《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());


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值