spring笔记3---如何使用指定的构造函数来构造bean

spring笔记1---基于spring框架的第一个程序 》和《spring笔记2---bean引用其他bean》这两篇文章中,都是使用默认的构造函数来构造bean,本文将描述如何通过指定的构造函数来构造bena。


1 修改Mobile类,为Mobile类增加一个构造函数,修改的Mobile类如下:

package com.gm.spring_test;

public class Mobile {
	private User user; // 手机使用者
	private String model; // 手机型号
	private Float price; // 手机价格
	
	@Override
	public String toString() {
		return "Mobile [model = " + model + ", price = " + price 
				+ ", user = " + user + "]";
	}
	
	public Mobile(String model, Float price, User user) {
		this.model = model;
		this.price = price;
		this.user = user;
	}

	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">
		<constructor-arg value="iphoneX" type="java.lang.String"></constructor-arg>
		<constructor-arg value="2999.99" type="java.lang.Float"></constructor-arg>
		<constructor-arg ref="User"></constructor-arg>
	</bean>
</beans>


3 使用bean:

ApplicationContext context = new ClassPathXmlApplicationContext("spring-conf.xml");
Mobile mobile = (Mobile) context.getBean("Mobile");
System.out.println(mobile);


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值