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